#discord-bots
1 messages Β· Page 4 of 1
Ignoring exception in on_typing
Traceback (most recent call last):
File "/home/runner/Official-public-bot/venv/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/runner/Official-public-bot/afk.py", line 28, in on_typing
self.data.remove(self.data[i+1])
NameError: name 'i' is not defined
can someone help me fix this
it does not remove my afk this is the code:
import discord
from discord.ext import commands
class boi_innit(commands.Cog):
def __init__(self,client):
self.client = client
self.data = []
@commands.command()
async def afk(self, ctx, *args):
msg = ' '.join(args)
self.data.append(ctx.author.id)
self.data.append(msg)
await ctx.send("AFK has been set!")
@commands.Cog.listener()
async def on_message(self, message):
for i in range(len(self.data)):
if (f"<@{self.data[i]}>" in message.content) and (not message.author.bot):
await message.channel.send(f"<@{self.data[i]}> **AFK:** {self.data[i+1]}")
return None
break
@commands.Cog.listener()
async def on_typing(self, channel, user, when):
if user.id in self.data:
self.data.index(user.id)
self.data.remove(self.data[i+1])
self.data.remove(user.id)
await channel.send(f"{user.mention} Welcome back!")
def setup(client):
client.add_cog(boi_innit(client))
How can i use a list of number like ```py
list = [123123, 342423, 3123123]
#then use that here
print(list)
#printing them in order?
command files
I didnt have different files in the gist so I simply skipped the different files thing
this is what the bot.py file looks like, do I put something here? in your example you are creating a bot but I create mine here
example of command file
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
i keep getting this error https://paste.pythondiscord.com/cibemafuxe
list = [123123, 342423, 3123123]
print(list)
``` how can i print each number individually
That's like very basic python
use a loop
Kill your terminal
Type kill 1 in shell
youtube wont teach that i looked verywhere
no you didn't
Free python courses will
i did
!resources also
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
i dont needd that to finish my project
You mean like 123123, 342423, ...
id say not to use replit tho πΆ
yep
Ya
oh wait that fixed it
yes
alr
Making a project without language knowledge is kinda weird don't you find
anyone good with buttons and view?
Yeah
You shouldn't define on_timeout by attribute assigning
Use subclassing it's not that hard
yeah yeah i know but i have already dont this
also subclassing for 2 buttons is meh
πΆ
You don't say
Take a look at these things https://github.com/Exenifix/AIAS/blob/e731bf0c7f08b14e48f575c690f646ff510d8802/utils/views.py#L32-L76
Subclassed but still easy to use
i just need some on_timeout thing, the commented one dosent work
it would be amazing if i could do it in command itself though
since i will find everything in one place
doing this right now
@commands.command()
@commands.is_owner()
async def droptb(self, ctx):
button1 = ui.Button(label="β
", style=discord.ButtonStyle.blurple,)
button2 = ui.Button(label="β", style=discord.ButtonStyle.blurple,)
async def button_callback1(interaction):
if interaction.user != ctx.author:
await interaction.response.send_message(content="fuk off bruv", ephemeral=True)
else:
await self.bot.db.exec_write_query("DROP TABLE users")
await self.bot.db.exec_write_query("DROP TABLE userss")
await interaction.response.edit_message(embed=embed2)
button1.callback = button_callback1
async def button_callback2(interaction):
if interaction.user != ctx.author:
await interaction.response.send_message(content="fuk off bruv", ephemeral=True)
else:
await interaction.response.edit_message(embed=embed3)
button2.callback = button_callback2
embed1 = discord.Embed(title="u doin it bruv?")
embed2 = discord.Embed(title="u did it bruv")
embed3 = discord.Embed(title="what a pussi bruv")
view = ui.View(timeout=30)
view.add_item(button1)
view.add_item(button2)
# view.on_timeout(DISABLED=True)
await ctx.send(embed=embed1, view=view)```
how to get from this list int member id?
[<Member id=35345345353535 name='PLATINADS' discriminator='7895' bot=False nick=None guild=<Guild id=545345345345 name='server' shard_id=0 chunked=True member_count=7>>]
what variable are you printing?
class MyView(discord.ui.View):
def __init__(self, buttons: list[discord.ui.Button], *, timeout=180):
super().__init__(timeout=timeout)
for button in buttons:
self.add_item(button)
async def on_timeout(self, inter)
...
And then you can use it like
view = MyView([discord.ui.Button(...), discord.ui.Button(...)], timeout=30)
Preferably to put the thing into a separate module and import it when needed
@odd mango
timed_out_members = [member for member in ctx.guild.members if member.is_timed_out()]
how do i make discord.py dm someone on join
And as for those checks in callbacks you can just define interaction_check in subclass and never have other users pressing the button
fetch_channel(userID)
Listen for on_member_join event and then just member.send()
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
DM channels have different IDs from user IDs afaik
Remove discord.
no i use my id in my bot while dming me errors
works fine
It's typically bot.get_user(id).send(...)
mhm
I once tried to send the DM message with raw discord API and just putting user ID to endpoint didn't work, the actual dm channel id was different
Β―_(γ)_/Β―
Do you have intents enabled
no
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
how i do that
You need member intent
that is my id
It's get_user dude
oi f
Lmao
Is there any java discord servers?
Thankyou!
turn them on in dev portal too
Not necessarily all
i mean i turn all on lol
He only needs default + members
all intents = useless ram consumption
yeah ig
u just need the 3 in dev portal
i got 8 π
Are you hosting on local pc
it didnt work still
but i host on 1gb ram
Send us your code.
so β οΈ
Dang
import os
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="-", intents=intents)
client = discord.Client()
@client.event
async def on_ready():
print("I'm in")
print(client.user)
@client.event
async def on_member_join(member):
await member.send("Welcome!")
token = os.environ.get("DISCORD_BOT_SECRET")
client.run(token)```
Don't use client
yeah
Use bot for everything
lmaooooo
ok
And I recommend using bot.listen() instead of bot.event
yeah way better
it works
Ight enjoy!
Small bots aren't really RAM consuming btw
If coded well
@vale wing how much ram you got??
That's a VPS it has like 3 or 4 gb
On my PC I got 16 gb
Very nice
Web development* Yes there will be.
Okayy
#web-development will be one place to start, but it all depends what you want to build in this web development.
But that is also off-topic, so you better asking either in above channel or an off-topic one π
@bot.event
async def on_command_error(ctx, MissingRoles):
if isinstance(MissingRoles):
error=discord.Embed()
error=discord.Embed(title=f" π€ ERROR π« ",description=f"{ctx.author} premium role is needed to run this command !",color=0xffff00)
raise error
await ctx.reply(embed=error)
```
When someone types a invalid cmd this shows up ^
is MissingRoles not a function?
isinstanceisn't used like thison_command_errorisn't used like thisMissingRolesis an exception- None of code after
raisewill be executed
ππ
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
Can you show me what it should look like??
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
what should it look like then??
Look at the docs I linked and figure it out ig?
Dang okay lol
This as well if you don't know about exceptions https://docs.python.org/3/tutorial/errors.html
how's this
class Buttons(discord.ui.View):
def __init__(self, *, timeout=30):
super().__init__(timeout=timeout)
@discord.ui.button(label="β
", style=discord.ButtonStyle.blurple)
async def button_callback1(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction_check(interaction)
await self.bot.db.exec_write_query("DROP TABLE users")
await self.bot.db.exec_write_query("DROP TABLE userss")
embed2 = discord.Embed(title"u did it bruv")
await interaction.response.edit_message(embed=embed2)
@discord.ui.button(label="β", style=discord.ButtonStyle.blurple)
async def button_callback2(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction_check(interaction)
embed3 = discord.Embed(title"what a pussi bruv")
await interaction.response.edit_message(embed=embed3)
@commands.command()
@commands.is_owner()
async def droptb(self, ctx):
embed1 = discord.Embed(title="u doin it bruv?")
await ctx.send(embed=embed1, view=Buttons())```
Perfect except embeds definition
oh why
The functions can't see embeds you defined in other functions
ugh
Or as classvars which you did
okay wait
self.embed2 or self.embed3
So basically the embeds must be defined inside callbacks
ok now?
And a useless edit view=self, you didn't do anything to a view
oki
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
okay take a look now
Yeah this is correct but now the init is kinda useless
oh and do i add author check in callback?
oh what else then
!d discord.ui.View.interaction_check override this
await interaction_check(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
Just remove it, your subclass will automatically use init from superclass which functionally doesn't differ from yours (besides the timeout default value)
welp i will let it be then if it functionally dosent differ
have a final look now
check if i am doing interaction check right and all
How would i add a role to a certain user??
async def mute(ctx,user:discord.User,*,reason="No reason given !"):
Reason="add here"
mute=discord.Embed()
mute=discord.Embed(title=f" Muted by {ctx.author}",description="Reason:",reason,color=0xffff00)
await add_roles("Muted")
```
what i got so far
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
how do i disable button on interaction or on timeout
@bot.command()
@commands.has_role("mod")
async def mute(ctx,user:discord.User,*,reason="No reason given !"):
Reason=None
mute=discord.Embed()
mute=discord.Embed(title="π€ Mute Command !",description=f"Muted by {ctx.author}",color=0xffff00)
await ctx.reply(embed=mute)
await add_roles("Muted",reason=None,atomic=True)
its not giving the user the role
discord.ui.View.stop()
check it out
!d discord.ui.View.stop
stop()```
Stops listening to interaction events from this view.
This operation cannot be undone.
Someone help
your embed has the same name of your function so your function is being overwrited, also Reason != reason
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
It doesnt work when i fixed it @glad cradle
for your case it's await user.add_roles(...)
i think you should use member object instead of user object
Nope @glad cradle
Not working
@bot.command()
@commands.has_role("mod")
async def mute(ctx,user:discord.User,*,reason=None):
Reason=None
mutee=discord.Embed()
mutee=discord.Embed(title="π€ Mute Command !",description=f"Muted by {ctx.author}",color=0xffff00)
await ctx.reply(embed=mutee)
await add_roles("Muted")
```
Can you show me what it should look like?? @glad cradle
Idk if it's much related to discord.py, but I have a subclass of commands.Bot where I edited the function close() with some other functions to close the connections to the aiosqlite database. this means that they get closed if the function is called, but does it also work on a script interruption?
try it
how
if I just press the exit button to the window
it just interrupts it
just add a print statement
see if there is some on event close or something idk
no there isn't
if I call that close function the bot goes instantly offline on ds
but if I only close the script it takes around 1/2 minutes
right
idk why that's so confusing 
Why bot does not detect commands of freshly added cog
can somebody help in vc in 30 mins?
@commands.Cog.listener()
async def on_invite_delete(self,invite):
embed=nextcord.Embed(color=0xfd9fa1, description= f'{invite}', title='Invited Deleted')
embed.timestamp=datetime.datetime.utcnow()
await self.bot.get_channel(933978399280599080).send(embed=embed)
```is there a way to change the embed so i can add who deleted in the invite?
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guildβs audit logs.
You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
!d discord.AuditLogEntry.user
!d discord.AuditLogEntry.action
The action that was done.
!d discord.AuditLogAction.invite_delete
An invite was deleted.
When this is the action, the type of target is the Invite that was deleted.
Possible attributes for AuditLogDiff...
https://github.com/DisnakeDev/disnake/blob/master/examples/views/button/paginator.py#L10-L17
how the .disabled things works?
examples/views/button/paginator.py lines 10 to 17
class Menu(disnake.ui.View):
def __init__(self, embeds: List[disnake.Embed]):
super().__init__(timeout=None)
self.embeds = embeds
self.embed_count = 0
self.first_page.disabled = True
self.prev_page.disabled = True```
i dont see an attribute to find who deleted the invite.. is there no way to track that then?
@austere vale
oh- im dumb
wdym by that
it sets the button the disabled
@app_commands.command(name="report", description="report a user.")
async def report(self, interaction: discord.Interaction, member: discord.Member,reason: str):
username1 = str(interaction.user)
if username1 == str(interaction.user):
embed4 = discord.Embed(description=f"{username1}, you **cant** ``report`` your self",color=color.color)
await interaction.response.send_message(embed=embed4)
else:
channel = self.client.get_channel(998907245809115288)
embed2 = discord.Embed(description=f"{member} has been reported for | ``{reason}``",color=color.color)
await interaction.response.send_message(embed=embed2)
embed = discord.Embed(title="FEEDBACK",description=f"**USERNAME** : {member}\n**USER ID** ``{member.id}``\n**REASON** : ``{reason}``\n**REPORTED BY** : {member}",color=color.color)
embed.set_author(name="REPORT", icon_url="https://cdn.discordapp.com/attachments/994115426894237759/999261257729331240/monophy.gif")
await channel.response.send_message(embed=embed)
thats my code, i do the command i report someone and its saying im still reporting my self how do i fix
uhh can you help me fix it?
embed=nextcord.Embed(color=0xfd9fa1, description= f'Deleted by: {nextcord.AuditLogAction.invite_delete.Member}\n{invite}', title='Invited Deleted')
see error and read docs
yes but, it's a function attribute? What is it?
you have to iterate through the audit logs async for entry in invite.guild.audit_logs(action=nextcord.AuditLogAction.invite_delete) and you can check the user with entry.user
oh an async inside an async
property with a setter
i got it! thank you so much
you can use your bot or client object
are you inside a cog?
File "c:\Users\grama\Desktop\PLATINA2\cogs\commands\for_user\fun\hug.py", line 28, in hug
embed.set_image(url = random.choice(hug))
File "C:\Program Files\Python310\lib\random.py", line 378, in choice
return seq[self._randbelow(len(seq))]
TypeError: object of type 'CogMeta' has no len()```
i get variable `hug` from external file
sorry i fixxed it
but i got one more thing
A bit difficult to do manually but I'm sure there are APIs that can do it for ya
How do I invite my bot to my server? Sorry, I'm new to this
!pypi art
https://discord.com/developers/applications
click on your application > OAuth2 > URL generator
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
It says 'please select a redirect url'?
no
https://discord.com/developers/applications/{Your_app_id_here}/oauth2/url-generator
Oh
btw follow these steps
Go to your application > OAuth2 > URL Generator > Select the scope Bot > Choose permissions > copy link
You should also select applications.commands if you plan to migrate to application commands in future
This is my script, but the bot does not seem to turn on?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='>', description="This is a Helper Bot")
@bot.command()
async def ping(ctx):
await ctx.send('pong')
@bot.command()
async def stats(ctx, player):
if player == "RandomDemon":
await ctx.send("RandomDemon - Wins: 0 - Losses: 0")
bot.run('[my token]]')
it's
bot.run('TOKEN_HERE')
without []], you need to pass it as string
I know, I just put that there so you wouldnt see the token
The brackets werent in there before
Any error?
It works now, but I didn't change anything????
Aight I got another question. Could I have another text file in the same folder as the py file, which information can be retrieved from? E.g, the text file says "RandomDemon - Runs: 5 - Hits: 3", and the script will fetch that info and send it?
Hey, lets say that I have two commands, I need to achieve that if any of those two comands is called, then I need to start a timer and in a specific time none of these commands can be executed, how can I achieve that? The code is underneath.
@client.command()
async def hello(ctx):
await ctx.send("Hello")
@client.command()
async def goodbye(ctx):
await ctx.send("Goodbye")
yes you can do this
!d discord.ext.commands.Cooldown
No documentation found for the requested symbol.
thank you! ive probably found souliton on stackexchange with cooldown
Could I make a command that refreshes my bot so any changes to the code go into effect?
are you using cogs?
if so you can create reload commands
No?
Oh okay that's good.. I forgot the explanation and coudn't find the tag for it lol
File "main.py", line 82
t = w.send_to(buyer_address, f'{amount * 0.000046} BTC', offline=False)
^
IndentationError: unindent does not match any outer indentation level
how to issue a built-in timeout in discord.py?
you mean an embed?
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
@quaint epoch
the line check=lambda put that on one line
wdym?
like confirmation = await bot.wait_for('on_message', check=lambda m:m.author==buyer)
put that all on one line
not two
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
it is
Should be await bot.wait_for('message', ...)
well paste it anyway
they both do the same thing
and it's a simple fix
Oh cool. Didn't know prefixing with on_ worked, the docs says to remove it lol
how to start python bot?
@quaint epoch still
python main.py
still?
send 3 lines above and below where the error occurrs
cd bot?
along with the line where the error occurs
if your bot is in kostas/bot, yes
i mean like in text, not images
if r.status_code == 200 or 201:
if 'bc1qfc3wdf0834qan0zye48z9klcxysy77yy6n0z46' in r.text:
embed = discord.Embed(
title=f"Received!",
description="You can now give the buyer your promised details, once the buyer gets it, we will send the funds to u.\nThe Buyer should confirm he got it by typing `confirm` in chat",
color=0x2f3136
)
await mm_channel.send(embed=embed)
confirmation = await bot.wait_for('on_message', check=lambda m:m.author==buyer)
t = w.send_to(buyer_address, f'{amount * 0.000046} BTC', offline=False)
read the error
i don't have access to your computer
find the dir where your bot file is, and do cd path
there's your problem
where
C:\Users\kostas\Desktop\bot
so do that
cd C:\Users\kostas\Desktop\bot
so go before t and tab
still doesntr work
if r.status_code == 200 or 201:
if 'bc1qfc3wdf0834qan0zye48z9klcxysy77yy6n0z46' in r.text:
embed = discord.Embed(
title=f"Received!",
description="You can now give the buyer your promised details, once the buyer gets it, we will send the funds to u.\nThe Buyer should confirm he got it by typing `confirm` in chat",
color=0x2f3136
)
await mm_channel.send(embed=embed)
confirmation = await bot.wait_for('message', check=lambda message: message.author == buyer)
t = w.send_to(buyer_address, f'{amount * 0.000046} BTC', offline=False)
it's unindented
you need to put 4 more spaces before t = ...
try reading it, it says that dateutil is not installed
how to install?
if r.status_code == 200 or 201:
if 'bc1qfc3wdf0834qan0zye48z9klcxysy77yy6n0z46' in r.text:
embed = discord.Embed(
title=f"Received!",
description="You can now give the buyer your promised details, once the buyer gets it, we will send the funds to u.\nThe Buyer should confirm he got it by typing `confirm` in chat",
color=0x2f3136
)
await mm_channel.send(embed=embed)
confirmation = await bot.wait_for('message', check=lambda message: message.author == buyer)
t = w.send_to(buyer_address, f'{amount * 0.000046} BTC', offline=False)
oops
python -m pip install dateutil
pip install dateutil
just fix the indents
if r.status_code == 200 or 201:
if 'bc1qfc3wdf0834qan0zye48z9klcxysy77yy6n0z46' in r.text:
embed = discord.Embed(
title=f"Received!",
description="You can now give the buyer your promised details, once the buyer gets it, we will send the funds to u.\nThe Buyer should confirm he got it by typing `confirm` in chat",
color=0x2f3136
)
await mm_channel.send(embed=embed)
confirmation = await bot.wait_for('message', check=lambda message: message.author == buyer)
t = w.send_to(buyer_address, f'{amount * 0.000046} BTC', offline=False)
!d dateutil
if r.status_code == 200 or 201:
if 'bc1qfc3wdf0834qan0zye48z9klcxysy77yy6n0z46' in r.text:
embed = discord.Embed(
title=f"Received!",
description="You can now give the buyer your promised details, once the buyer gets it, we will send the funds to u.\nThe Buyer should confirm he got it by typing `confirm` in chat",
color=0x2f3136
)
await mm_channel.send(embed=embed)
confirmation = await bot.wait_for('message', check=lambda message: message.author == buyer)
t = w.send_to(buyer_address, f'{amount * 0.000046} BTC', offline=False)
you have to resinstall it
its indented?
yes it is, stop spamming it
still doesnt work
reinstall python?
yup
in place install should work
remember to add it to the path
and change your interpreter in PATH
it still gives indent errors? try asking in #python-discussion
since this is more of a general problem now
so i need delete and dowload this?
yup
ok
same problem
someone help
await message.author.timeout()
AttributeError: 'Member' object has no attribute 'timeout'
Make sure you're on v2.0
I ran pip install discord again. I have 1.7.3 installed. Why hasn't the library been updated?
It's not on pip
you have to install it manually
check the discord.py github homepage for instructions on how to do that
try float(amount)
Thank β€οΈ
itsz a indent issue
class Select(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="Option 1",emoji="π",description="This is option 1!"),
discord.SelectOption(label="Option 2",emoji="β¨",description="This is option 2!"),
discord.SelectOption(label="Option 3",emoji="π",description="This is option 3!")
]
super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "Option 1":
await interaction.response.edit_message(content="This is the first option from the entire list!")
elif self.values[0] == "Option 2":
await interaction.response.send_message("This is the second option from the list entire wooo!",ephemeral=False)
elif self.values[0] == "Option 3":
await interaction.response.send_message("Third One!",ephemeral=True)
class SelectView(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
self.add_item(Select())
@app_commands.command(name="help", description="list all commands")
async def help(self, interaction: discord.Interaction):
await interaction.response.send_message("work",view=SelectView())
error:
File "/home/runner/pls-donates/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 674, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: NameError: name 'SelectView' is not defined
@bot.event async def on_message(message): msg_content = message.content.lower() antiad = ["discord.gg", "dsc.gg"] if any(word in msg_content for word in antiad): if message.author.guild_permissions.administrator: pass await bot.process_commands(message) else: embed = discord.Embed(description=f"**Anti-AD**\nβ¨ γ»You dont have permission\nβ γ»To send links\nβ γ»Contact support for help") embed.set_footer(text="β Β Creator Matija#4633 β Β ") embed.set_image(url=f"https://cdn-longterm.mee6.xyz/plugins/welcome/images/964470380129550416/24c6d5ea24030caedb741ccbaebec30fe61375c3e218da8c75afa108002eb4d9.gif") await message.channel.send(embed=embed) await message.delete() else: await bot.process_commands(message)
Why users can bypass antiad if users edit message?
my bot worked as normal
in a test server but once i add it to a new server, it breaks and gives this error: TypeError: new() got an unexpected keyword argument 'deny_new'
because it doesn't come through as an on_message event
How can i fix it?
make another event listener for message edit
anyone?
Quick question, can i have a buttons view and dropdown view on a message? Two views total
You can have 5 items per view, and one view per message
Ughhhhh rip, this will be a pain then as i just relised that after coding everything and relised oh wait how do i put two views in a message
Looks like i gotta change smthing lmao, thanks
You can have one view, but you can also have both buttons and dropdowns in the same view
Oh wait, really?
5 rows per view, 5 items per row. Exceptions: dropdown menu counts as 5 items, so 1 dropdown menu per row
Total of 5 dropdowns, or 25 buttons
Well thats helpful but still pain to edit, i litterly have like 25 views rn that all loop thru eachother with args being passed thru eachother everywhere π
tyty for helping
Is it the one with the quotes and disabling them?
Yep
Right. I can see why that'd be a pain
Currently only half done about 20 views so far
π
Litterly aids, and i had to go thru and edit all the args bc i had one named "channel" wihtout knowing that would overwrite interaction.channel
Anyways have a good day and thanks again for helping
O wait i do got onen more question i might as well ask before ripping my brain out
So this grabs a artists portfolio and sorts starrred images and unstarred images into two lists then adds them together so starrred images are at the top of the dropdown right
Got any ideas how i could limit it to 5 images? Where starred images are always the first 5 but if theres only 3 starred images lets say, it grabs two other images that arnt starred
Wait oh i think i can do something where when both lists add up to 5, break
If len(starredlist + everythinglist) == 5:
break
Wait no
As that wont sort it out so it picks starred first
You're on the right track. Add them together, and get the first 5
(starred_list + everything_list)[:5]
Firstly, you'll want to rename your variables, go for the snake case convention of word_with_spaces_replaced_as_underscores, and a meaningful name, it makes it so much easier to read, and for others to help you.
Secondly, as Robin said, beat me to it lmao
You think those var names are bad? God you havnt seen the worst of it
when i cant think of a var name i either
a) keyboard smash
b) write out a whole sentance without any spacing π
such a pro dev move !
Also dropdowns can have 25 options in them, so it might be more sensible to get the first 25 with the starred images up top
But as that's a design choice I'll leave that up to you
True and i have that with /portfolio view
But this is for whne a quote gets sent, so its just a simple 5 images for the user
As there will be multiple quotes and faster for the user
Thats why starred are first too so the artist can pick out there best art to show up first
Ahh, I see. Though, respectfully, that's not something you should be proud of to tell others. It makes it difficult for you and others.
There are definetely worse things to be proud of.. this is minor, easy fix, though a bit of effort
When your pulling a all nighter and its 4 am, all i want is to just get it done lol
brain dosnt work right
Once you do fix it, I'd suggest getting a linter of sorts and set up strict rules
A what?
Like flake8. It helps you make sure your code is consistent with pep8 or any other rules you may have set (proper naming, max line length, etc)
Are type checkers part of linters too?
Ah, not sure how to do that tho lmao
What command do you code for your bot rn ?
?
what can your bot do ?
PyCharm has it built-in, but there are a couple you might find useful to disable or edit, e.g. max line length to 125 or another number you like, instead of the default 80 something
Mine? Just a commission thiny, got portfolio cmds and a ticket system lol. Not done tho
Maybe. But linters don't really concern themselves with types
Oh nice
Oh and paypal invoices im proud to talk about as that was pain !
amazing ! And itβs a discord bot or nothing like that ?
Ah yeye, thanks
The fact i got like 200 warnings for var spelling rn prob isnt a good start tho
Lmao
Disc bot
ok ok thatβs really cool
And gonna be honest i got zero clue how this would work but im still just gonna try it lmao
Anyways thanks for the help, prob be back within a hour after two more enery drinks and wanting to rip my skin off, pce
First part is simple. It just adds to 2 lists together, you can probably guess how that works. The [:5] is a little more interesting. It's slice notations, which follows this syntax:
my_list = [...] # pretend this has some items in it
my_list[start:stop:step]
start - the index to start at, starting at 0
stop - the index to stop at, exclusive.
step - the number of indexes to skip
in our example, [:5] is equivalent to [0:5:1] which means start at index 0, go until index 4, and skip by 1. This effectively gets the first 5 elements
Interesting things you can do are [::-1] which reverses a list, equivalent to [0:-1:-1] Negative values indicate the last element. -2 would indicate the 2nd to last element, -3 third to last element, you get the point.
Ooo, cool haha
Thanks!
Oh yeah and another question rq sorry
https://i.leaked-your.info/Y9PMH7zW
Did i mess something up here or, as https://discord-edating.com/bnfE5iYC
0 clue why im getting that
Interaction.guild.get_channel is getting the ticket channel
and thats being set to a var object, to get the message from
get_message is not a thing
It'd be almost impossible to cache that
You could use bot._connection._get_message()
But you're not supposed to be using that as it's internal
I'm quite sure. For e.g. dispatch isn't documented, but safe to use
Wait oh its fetch_message
Sometimes you don't need fetch_message, and you could construct a PartialMessage
One less API request :)
What exactly do you do with the message?
Just edit it, the message is the quote
A PartialMessage will suffice then
The code is just getting the message and editing the artists quote
get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialMessage "discord.PartialMessage") from the message ID.
This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
Changed in version 2.0: `message_id` parameter is now positional-only.
discord.py has some wonderful docs, they're really pleasant to read and make sense, I strongly suggest you take a look at em'
I do alot lol, just some things i dont even know what to search for. The get message thing tho yeah i prob should of just searched for that myself
For example if you look here, you'll see that there is no such thing as get_message
The closest thing you have is get_partial_message, which has these methods:
Ikik i was getting it confused for fetch_message
Wait, how would i have a view for buttons and a dropdown?
Or did i missunderstood you
You'd just use @discord.ui.button and @discord.ui.select, nothing special
Wait oh
Would i just pass both into here then or?
https://discord-edating.com/NuOw60mZ
bro that's the weirdest website I've seen in a while
Oh if you're subclassing discord.ui.Select like you are, you could just do self.add_item(UserViewQuote()) inside your view subclass
Yeah but what about for the buttons then
https://i.leaked-your.info/652dOsEI
https://discord-edating.com/mM427plD
this was the only way i learned how to make dropdowns and buttons lmao
This is a slightly more advanced version. If you're not doing anything special and your views are static, there's an easier way
Please do tell, as for the 50 thousond buttons and dropdowns there are
I would love to know
I think in your case you could benifit from the easier method
Here, I can write a quick example for you
Tyty that would help alot LOL
does anyone know a good tutorial for learning how to make python bots/.
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=60) # this is important, pass in the discord.ui.View attributes here
@discord.ui.button(label='Click me!', style=discord.ButtonStyle.green) # regular button stuff
async def button_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
# handle button press here
@discord.ui.select(placeholder='Choose something...', max_values=3) # regular select stuff
async def select_callback(self, interaction: discord.Interaction, select: discord.ui.Select):
# handle select here
@indigo pilot
in my this loop, it is supposed to ping user just once, still it keeps pinging user while deltime >= datetime.now() >= record.time
@tasks.loop(seconds=1)
async def background_loop_new(self) -> None:
await self.bot.wait_until_ready()
all_records = await self.bot.time_db.all_records()
for record in all_records:
channel = self.bot.get_channel(record.channel_id)
deltime = record.time + timedelta(seconds=5)
if deltime >= datetime.now() >= record.time:
await channel.send(f"<@{record.user_id}>, your drop cooldown is over.")
await self.bot.time_db.delete(record.user_id)
elif datetime.now() >= deltime:
await self.bot.time_db.delete(record.user_id)```what could be the problem?
Ooooooo
Tysm! I never knew this
Ill use that for what im doing with the portfolio images + accept quote button haha
it is supposed to ping once and delete the db so it can't ping again even while deltime >= datetime.now() >= record.time
Easiest way would be to add a break inside the if statement
what would that do?
It'd break out of the loop once it pings the user and deletes from the db
interesting, but loop will repeat itself again in next second
wouldn't it ping again then?
Well if you deleted it from the db, then they wouldnt be in the db to ping again right?
it is still supposed to delete yet is pinging
Well check, did it really delete from the db or
it keeps pinging so for the fact it didn't delete
but it lets me register with primary key again without a duplicate key error so it gets deleted at some point
I know for button i need to add a custom_id, but is there anything for the select menu? (so it wont timeout)
Yes, custom id works for select menus too
I think this example I wrote might help you: https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
Unfortunately I didn't show how to use custom_id in it, but it's still a decent resources nonetheless
Yeah but do i need it/anything else? So i tdosnt timeout
Other the specifying the actual timeout? no
Okay, tyty
!d discord.ext.commands.Context.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
Ik alr, thanks tho
!d
e.
Yo robin // anyone else
https://discord-edating.com/Tl1Jt9Dr any ideas how i can pass options thru?
At the decorators scope you don't have access to self
So you cannot do @deco(self.attr)
What are the options supposed to be? Are they procedural
There just a list of dropdown options
Passed in from a button
Yea ik thats why i am asking xD
Litterly the only way i can think of is global vars but.. thats disguating
Instead of using the decorator to construct the Select menu you could make a subclass
Then in that context using __init__ it'll have options if you pass it from the UserQuote's class constructor method
Then just manually add it view add_item
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
Yeah thats what i do with other things just didnt wanna do it with this as i got a button too that needs to be in the view
Guess i can addd two items i think
how would i make a variable specific to a player?
Are there somebody else that have problems with setting up your discord bot on heroku?
class UserQuoteButton(discord.ui.Button):
def __init__(self, channelvar):
self.channelvar = channelvar
super().__init__(label='Accept quote', emoji="π‘", style=discord.ButtonStyle.green, custom_id='agds')
async def callback(self, interaction: discord.Interaction):
pass```
is this right? never used subclassed buttons before
@app_commands.command(name="sendticketmessage", description="ADMIN | Send ticket message.")
@app_commands.checks.has_role(requiredrole)
@app_commands.guilds(serverid)
async def sendticketmessage(interaction: discord.Interaction):
view = TicketButtons()
embedd=discord.Embed(title="ποΈ Tickets", description="To create a ticket, please click one of the buttons below..\n\n**π¨ Commissions**\n\n**β Applications**\n\nβ **Support**", colour=0x33ECFF)
await interaction.response.send_message(embed=embedd, view=view)
@sendticketmessage.error
async def sendticketmessage_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingRole):
embed=discord.Embed(title="β No permission", description="You do not have the required permission to run this command!", colour=0xff1100)
embed.add_field(name="Role required:", value=requiredrolemention)
await interaction.response.send_message(embed=embed)
return
raise error```
how do i make my bot send a message when a specific user in my server is mentioned? this is just for fun in my server
With on_message
just start the beginning with "on_message", nothing else before? sorry i'm using discord.py after a year, i'm rusty
On_message is a event
so do the event
then if message == "what ever you want":
do stuff
Heres the docs for onmessage
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botβs own messages and private messages are sent through this event. This can lead cases of βrecursionβ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
oh ok thank you so much
how would i make a variable specific to a user?
If I wanted to make a bot that when you send a command it fetches a quote from a quote generating website, how would I got about doing that?
async def on_message(message):
if (message.guild.id == 988568558739013703) and (657011579115667479 in message.mentions.id):
await message.channel.send('Give Detraits Admin')```
what's wrong here?
do you know?
Whats the error
It's not
Hello robin
anyone knows about this error?
how'd you block for 2 hours lol
no idea what is blocked exactly, nor how this happened :o
time.sleep(6491)
π

(657011579115667479 in message.mentions.id) is wrong
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
interate in the list: (657011579115667479 in message.raw_mentions)
try that
oh wait nope
Replace message.mentions with message.raw_mentions
Using just mentions will be a list of User | Member's
is the "anonymous" parameter not valid? it's not showing up on the bot...
raw_mentions is just the ID
alr alr
@prisma wedge
wdym its not showing up, can you show an image of what's wrong

i cant help 
π
@slate swan
- discord.app_commands.errors.CommandSignatureMismatch: The signature for command 'ask' is different from the one provided by Discord. This can happen because either your code is out of date or you have not synced the commands with Discord, causing the mismatch in data. It is recommended to sync the command tree to fix this issue.```
im confused
fyi the whole bot worked before i added the anon option
how do you add slash commands?
So.. this didnt work for some reason, i added 6 portfolio images for testing but its showing all 6 instead of 5. Hhmm
everythingelselist = []
for imageid in artistdict['portfolio']['images']:
if (starredlist + everythingelselist)[:5] == 5:
break
if artistdict['portfolio']['images'][str(imageid)]['starred']:
#stuff
else:
#stuff
Right?
What's this part supposed to do? Some context would be helpful
I heard discord will be removing prefix commands, is that true?
Remember frombefore lol, the only get 5 images. Where to only get starred images first
Wait
Oh
Nevermind thats my fault i see
Sorry
Discord.py got me acting funny when reading some of the stuff they do
Well, short answer: yes. Long answer: no, discord can't really "remove" prefix commands. What they are doing is making a change that will make it almost impossible to make prefix commands. Verified bots that are in > 80 guilds will not get message content intents. Which means that when you get a new message created event, it won't have the content of the message. The only thing you know is that someone sent a message, and you know who that someone is, what time they sent it at, and some others but you won't know what the message actually is. And since prefix commands at their core work off the message content, this all but makes them impossible to work with
!d asyncio.exceptions.TimeoutError
nani
So this only really affects the big bots, right? If I want to make a personal bot for my server with prefix commands I still can?
is bot gas lighting me?
!d asyncio.TimeoutError
exception asyncio.TimeoutError```
The operation has exceeded the given deadline.
Important
This exception is different from the builtin [`TimeoutError`](https://docs.python.org/3/library/exceptions.html#TimeoutError "TimeoutError") exception.
Also what was the point of that
Yep. Just make sure you turn it on in your bot's dashboard, as I believe it's turned off by default. You'll also need to enable it within your code. Verified bots have to put in an application to discord requesting the intent, and why they need it, so compared to that clicking a button and adding in an extra line of code should not be that big of an issue
okay, thanks
Ive been here so much today, π
how can i get a local image to a embeds image?
I tried doing file = discord.File(f"local/PORTFOLIO_{str(id)}.png", filename=f"PORTFOLIO_{str(id)}.png") embed.set_image(url=f"attachment://PORTFOLIO_{str(id)}.png") but the image just dosnt show up in the embed, and theres no errors
if interaction.user
i tried that
What's your code?
class Select(discord.ui.Select):
def __init__(self):
options=[
discord.SelectOption(label="moderation",emoji="",description="list all moderation commands"),
discord.SelectOption(label="fun",emoji="",description="list all fun commands"),
discord.SelectOption(label="Slash commands",emoji="",description="list all slash commands")
]
super().__init__(placeholder="Select an catergory",max_values=1,min_values=1,options=options)
async def callback(self, interaction: discord.Interaction):
if interaction.user:
if self.values[0] == "moderation":
embed = discord.Embed(title="moderation commands",description="``/ban`` - [member] <reason>\n``/unban`` - [user_id]\n``/kick`` - [member] <reason>\n``,slowmode`` <time>",color=color.color)
await interaction.response.edit_message(embed=embed)
elif self.values[0] == "fun":
embed2 = discord.Embed(title="fun commands",description="``,coolrate`` [member]\n``,gayrate`` [member]",color=color.color)
await interaction.response.edit_message(embed=embed2)
elif self.values[0] == "Slash commands":
embed3 = discord.Embed(title="slash commands",description="``/report`` - [member] <reason>\n``/event`` - [url] <description> {button_name}\n``/killa`` - how to join killa",color=color.color)
await interaction.response.edit_message(embed=embed3)
else:
return
class SelectView(discord.ui.View):
def __init__(self, *, timeout = 180):
super().__init__(timeout=timeout)
self.add_item(Select())
@client.command()
async def help(ctx):
embed = discord.Embed(title="help",description="help command for **donate** coded in **dpy 2.0.0** ",color=color.color)
await ctx.reply(embed=embed,view=SelectView(),mention_author=False)
@hazy oxide
whenever I run my code I get
AttributeError: 'Intents' object has no attribute 'message_content'```
How do I fix this?
main.py:
in discord portal
turn all of this on
yup turned it all on
is it working?
yea
remove the two lines below __init__ u have already declared it in super()
wel, it worked. Now I got another problem
discord.ext.commands.errors.CommandNotFound: Command "clear" is not found```
this is the command I was trying to use
did u sync?
in setup_hook add await self.tree.sync()
it was with "bot" and I changed to self, but still the same error
remove guild
still nothing
also last line of setup_hook add return await super().setup_hook()
dpy doesn't implement anything there, so no use really
Also if the only thing you subclass the Bot/Client for is overriding setup_hook you can just do ```py
bot = Bot(...)
@bot.event
async def setup_hook() -> None:
... # do stuff
bot.run(...)
do you know what it is? :o
lmao
Especially the stack part
yea lol
that question isn't related to Discord bots. ask in #python-discussion or in a help channel (see #βο½how-to-get-help)
ok mod
can bots use custom emojis in their about me?
How can I add optional command arguments with prefix?
like command -option1 -option2 and then use the -option to call another function within command
just make sure to set a default value to parameters
I dont see why not
yeah it works
for some reason animated emojis are really small though
Setup hook isnt a event
how to get guild id without function?
ctx.guild.id
hello
my Bot is not running, when I run the bot.py file it seems like it's doing something but it does nothing
this is my code
# IMPORT DISCORD.PY. ALLOWS ACCESS TO DISCORD'S API.
import discord
# GETS THE CLIENT OBJECT FROM DISCORD.PY. CLIENT IS SYNONYMOUS WITH BOT.
bot = discord.Client()
# EVENT LISTENER FOR WHEN THE BOT HAS SWITCHED FROM OFFLINE TO ONLINE.
@bot.event
async def on_ready():
# CREATES A COUNTER TO KEEP TRACK OF HOW MANY GUILDS / SERVERS THE BOT IS CONNECTED TO.
guild_count = 0
# LOOPS THROUGH ALL THE GUILD / SERVERS THAT THE BOT IS ASSOCIATED WITH.
for guild in bot.guilds:
# PRINT THE SERVER'S ID AND NAME.
print(f"- {guild.id} (name: {guild.name})")
# INCREMENTS THE GUILD COUNTER.
guild_count = guild_count + 1
# PRINTS HOW MANY GUILDS / SERVERS THE BOT IS IN.
print("SampleDiscordBot is in " + str(guild_count) + " guilds.")
# EVENT LISTENER FOR WHEN A NEW MESSAGE IS SENT TO A CHANNEL.
@bot.event
async def on_message(message):
# CHECKS IF THE MESSAGE THAT WAS SENT IS EQUAL TO "HELLO".
if message.content == "hello":
# SENDS BACK A MESSAGE TO THE CHANNEL.
await message.channel.send("hey dirtbag")
# EXECUTES THE BOT WITH THE SPECIFIED TOKEN. TOKEN HAS BEEN REMOVED AND USED JUST AS AN EXAMPLE.
bot.run("{token}")
you need to enable message content intent I think
sorry I haven't coded in a while, it's been a while since I made a discord bot, how do I do that, AKG?
!d discord.Intents
class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.
Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.
To construct an object you can pass keyword arguments denoting the flags to enable or disable.
This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
New in version 1.5.
# IMPORT DISCORD.PY. ALLOWS ACCESS TO DISCORD'S API.
import discord
intents = discord.Intents.default()
intents.message_content = True
# GETS THE CLIENT OBJECT FROM DISCORD.PY. CLIENT IS SYNONYMOUS WITH BOT.
bot = discord.Client(intents=intents)
# EVENT LISTENER FOR WHEN THE BOT HAS SWITCHED FROM OFFLINE TO ONLINE.
@bot.event
async def on_ready():
# CREATES A COUNTER TO KEEP TRACK OF HOW MANY GUILDS / SERVERS THE BOT IS CONNECTED TO.
guild_count = 0
# LOOPS THROUGH ALL THE GUILD / SERVERS THAT THE BOT IS ASSOCIATED WITH.
for guild in bot.guilds:
# PRINT THE SERVER'S ID AND NAME.
print(f"- {guild.id} (name: {guild.name})")
# INCREMENTS THE GUILD COUNTER.
guild_count = guild_count + 1
# PRINTS HOW MANY GUILDS / SERVERS THE BOT IS IN.
print("SampleDiscordBot is in " + str(guild_count) + " guilds.")
# EVENT LISTENER FOR WHEN A NEW MESSAGE IS SENT TO A CHANNEL.
@bot.event
async def on_message(message):
# CHECKS IF THE MESSAGE THAT WAS SENT IS EQUAL TO "HELLO".
if message.content == "hello":
# SENDS BACK A MESSAGE TO THE CHANNEL.
await message.channel.send("hey dirtbag")
# EXECUTES THE BOT WITH THE SPECIFIED TOKEN. TOKEN HAS BEEN REMOVED AND USED JUST AS AN EXAMPLE.
bot.run("{token}")β
Try this
# CLIENT IS SYNONYMOUS WITH BOT.
not really
that's if you're talking about commands.Bot
Also you need to enable message_intents in discord developer portal too
This code is questionable
Permissions are not intents, the intents are located under bot tab
why do you have so many comments
And why are they caps π³
I took it from a website to start my bot
Nice another copypaster
probably should look up a more recent tutorial
well like I said I haven't coded in a while this is just to get me started
Yeah that's totally a better thing
I am not gonna be copying other bots
!resources there's a guide about dpy iirc
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Actually it's here https://www.pythondiscord.com/pages/guides/python-guides/discordpy/
A learning guide for the discord.py bot framework written by members of our community.
ok
why are you doing that
@bot.event
async def on_ready():
# PRINTS HOW MANY GUILDS / SERVERS THE BOT IS IN.
print(f"SampleDiscordBot is in {len(bot.guilds)} guilds.")
Oh well i just copied this guy/girl's code and added some stuff to it to try make it work
Np (not sure how I helped but ok)
the website you gave had an updated version of how you can run your bot and I tried it and it's now running
And btw about hosting your bot, what do you think about using heroku?
That's a bad idea although I didn't try it myself
@leaden seal
what should i use then?
i use replit
like Virtual Machines?
Yeah
oh well the bot i made in replit has over 1000+ lines of code and its still working
1000+ lines in one file or?
yea one file
You'd better rewrite it to cogs and modules then
Everything in one file is inefficient and hardly maintainable
yee,thanks i'll try doing that
Gl
how much does a VPS cost?
depends on your provider
Galaxygate has options for 3$/mo, some services provide free trial
ok well I'll use heroku until I am sure to buy a VPS
Like digitalocean, azure and aws. Good thing about aws is that it gives free tier server for 1 year but a bad thing is it's not very user friendly
beginner friendly
Not AWS.
Unless you have a technical background, AWS, Azure and GCP should be avoided for things like this, seen way to many people rack up bills in the 1000s.
what's the difference between a setup and a requirements file?
and which one should I use?
the setup is a method of the Client or Bot class, it is used to load Cog objects which are created by subclassing the Cog class inside a file, it is a way to organize the directory of your project
For the requirements, if you mean the requirements.txt file, it is a file which can be used with the command pip install, specifying that directory the pip command will install all the package declared inside the requirements file
ok
is (command.cog) best way to create bot commands ? or i missing something op ?
command.cog is a parameter which returns the Cog if the command belongs to a cog or None if there isn't one 
wdym?
gimme a sec
for command in cog.commands:
command.add_check(check)
how do I check the version of a pip installed package like discord.py?
this you mean?
Hey guys, I'm trying to make my Discord bot join the voice channel I am in, however, my bot will not join despite everything else in the function working as intended, I think it is just the await channel.connect() that is problematic and 'connected' will not print.
@commands.command()
async def join(self, ctx):
if not ctx.author.voice:
await ctx.send(f"{ctx.author.mention} You are not connected to a voice channel. Please join a voice channel before using this command.")
return
else:
print('yes')
channel = ctx.message.author.voice.channel
print(channel)
await channel.connect()
print('connected')
pip freeze in the shell
You could do
pip show [package_name]
ok thanks
decorators are better tbh
i want this @commands.check(is_owner) to whole class at onle
once*
can i ?
Nevermind, turns out I didn't install the discord.py[voice] package. https://cdn.discordapp.com/emojis/755086077051797514.webp?size=64
or i have to use it in every decorators
What does he want from me? (Updated to 2.0)
is it not in main pakage ?
Apparently not
whats voice client file then π€
wdym?
from discord.ext.commands import CheckFailure, check, Context
class MyCustomCheckError(CheckFailure):
def __init__(self, message):
self.message = message
super.__init__(message = self.message)
def my_custom_check():
def predicate(ctx: Context):
if ctx.author.id == ctx.guild.owner_id:
return True
raise MyCustomCheckError("You're not the owner")
return check(predicate)
#when declaring a command
@commands.command()
@guild_only()
@my_custom_check()
async def your_command(ctx: Context):
#this will raise MyCustomCheckError if the caster is not the owner of the guild
Blvck coming in with the haymaker
What is tracemalloc?
You probably didn't await a coroutine
add_cog is a coroutine now
You're on discord.py 2.0
Yes
As we are laughing at someonr in vc for flirting with someone with a boyfriend i'll leave this for other peeps

And... ?
like i have 9 different your_commands in class , mean i have to type @my_custom_check() 9 times in each command right ?
just @my_custom_check()
btw whats @guild_only() ?
await it
Makes command guild only
So it's not usable in dms
oh kk
!d discord.ext.commands.guild_only
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
got it
How? If I do it outside of async def it will swear
Or... Should this be done in on_ready?
setup_hook prolly
async def setup_hook?
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
Thank
For the command to work in the same channel?
No no I want command work in only one channel
Simple words i want channel check
I still don't quite understand. Are there any examples?
class Client(discord.Client):
async def setup_hook(self):
# do setup here
Thank you, I'll try
You can make a command group and use the deco only to the father command, it will work anyways
i have file text.py
import discord
test_embed = discord.Embed(description = guild id)
and my main command file
from discord.ext import commands
from text import test_embed
class MyCommand(commands.Cog):
def __init__(self, client):
...
await ctx.send(embed = test_embed)
...
how to get guild id in text.py?
Parameters
?
!e
def uwu(value: str):
print(value)
uwu("the uwuest string in the world")
@placid skiff :white_check_mark: Your 3.11 eval job has completed with return code 0.
the uwuest string in the world
π
import discord
from discord.ext import commands
class boi_innit(commands.Cog):
def __init__(self,client):
self.client = client
self.data = []
@commands.command()
async def afk(self, ctx, *args):
msg = ' '.join(args)
self.data.append(ctx.author.id)
self.data.append(msg)
await ctx.send("AFK has been set!")
@commands.Cog.listener()
async def on_message(self, message):
for i in range(len(self.data)):
if (f"<@{self.data[i]}>" in message.content) and (not message.author.bot):
await message.channel.send(f"<@{self.data[i]}> **AFK:** {self.data[i+1]}")
return None
break
@commands.Cog.listener()
async def on_typing(self, channel, user, when):
if user.id in self.data:
self.data.index(user.id)
self.data.remove(self.data[i+1]) #it shows a red line under[i+1]
self.data.remove(user.id)
await channel.send(f"{user.mention} Welcome back!")
def setup(client):
client.add_cog(boi_innit(client))
so when i type the bot does not responf with welcome back
how can I fix it?
Why doesn't member.is_avatar_animated() work in 2.0?
- Use dict for this, what tf for is adding 2 separate types of data into single list and then doing all those i+1
- For checking the afks you might want to use
message.mentionswhich contains a list ofMemberobjects which is more convenient to operate with
nvm i got it fixed
btw how does a music system work in discord.py?
!d discord.VoiceClient.play
play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource "discord.AudioSource").
The finalizer, `after` is called after the source has been exhausted or an error occurred.
If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.
Changed in version 2.0: Instead of writing to `sys.stderr`, the libraryβs logger is used.
https://discordpy.readthedocs.io/en/latest/migrating.html?highlight=is_avatar_animated read the docs, they are very useful.
with slash commands, is there a way to make it run in all guilds?
cant run it at the moment, but i got this from the github
Found β€οΈ
if i get api unbanned i'll mess around
top kek
tried setting the id to 0 and got a forbidden error
so cringe π’
cant find much
that sucks
@vernal sphinx do you mean like sending two messages with one command
sending two embeds in message
the thing is, it kinda looks ugly on phone when sending multiple embeds in different messages. It appears as new messages which i kinda annoying so if the embeds are clumped up, it would like nicer
define first embed as e1 and second one as e2
await ctx.send(embed=e1)
await ctx.send(embed=e2)
thats how i would do it
thank me when it works π
haha
help pls i was bored so i thought why not start coding on my discord bot again but it doesnt work anymore im 100% sure it did 2 months ago
gamers π how to get slash commands to work in all servers
Can u send your full code?
sure
Alr
1 sec
i kinda lost it... my folders are 1 big mess
Oh damn
Arent self bots not allowed
yes... but i was playing around whit it
and now its broken lol
Oh well the newest version is 1.7.3 but im using the 2.0 version(rewrite)
you can get banned for self bots btw
yeah
ye never used it in servers only in private servers whit friends
still isnt allowed
why not tho
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Selfbotting is very much against Discord's ToS
i didnt write the discord tos
how can i fix my discord bot whit that?
Oh well if you want to install the 2.0 vers just do this in the terminal: pip install git+https://github.com/Rapptz/discord.py
after you install it you might wanna add some intents to your code
alr ty ill try that
Okok gl gl
man i get close then i forget what i want to do
get it to work with one guild, but i want the commands to work on all guilds
btw is it fine if you just download the latest git?
i didnt have it
I guess so,yes
my code keeps giving this error
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "clear" is not found```
the command in question
this is something like 100 ppl may have asked, but...
which lib is the "best" one now? dpy disnake, or idk anythingelse ?
try
import os, discord, datetime
idk if its proper but it looks better
hmmm ok, works for me idk
OMG I GOT IT
import discord
from discord import app_commands
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
@tree.command()
async def test(interaction: discord.Interaction):
await interaction.response.send_message("install gentoo")
@client.event
async def on_ready():
await tree.sync()
print("broken")
client.run("HJjhjdsds&&89ds8s88")
now my bot has a cool badge
Try to use fetch instead of get
@client.command()
@commands.has_permissions(administrator = True)
async def set_prefix(ctx):
prefix = "!"
file = "prefix.txt"
if prefix == "!":
await ctx.send("Prefix set to !")
else:
await file.read("prefix")
``` idk i need help making a set prefix command multi guild, using files aka txt, can someone help me#
what do you think the fastest image format for discord embeds is?
out of these assuming the same size: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff
How to "reload" the bot with command?
wdym? like restart the bot?
guys i need help making a set prefix command for multiguild, using txt
yes, i tried bot.close() and bot.start()
wrong libk
JPEG/PNG are the fastest when it comes to loading times, JPEG being the faster one but lower quality. PDF isn't an image file but more of document.
this works for me
@commands.command()
@commands.is_owner()
async def restart(self, ctx: commands.Context):
await ctx.send("`$ restarting bot...`")
os.system("clear")
os.execv(sys.executable, ["python"] + sys.argv)
lemme send u a version that works without cogs
@bot.command()
@commands.is_owner()
async def restart(ctx):
await ctx.send("`$ restarting bot...`")
os.system("clear")
os.execv(sys.executable, ["python"] + sys.argv)
ok try doing this instead:
@bot.event
async def on_member_join(member):
if member.guild.id == theguildid:
welcome_channel = await bot.fetch_channel(channelid)
await welcome_channel.send(themessage)
jpg is probably just faster due to size though right?
@real grail hope this helps
there @native heart
i need to rewrite this
wdym no?
Isn't there a built-in function in discord.py for this?
idk i just use that
works π€·ββοΈ
Possibly, my assumption is its faster due to its lower quality image it produces, so you could have a gif, png, jpeg, etc. all at the same KB, but JPEG will load faster due to the lower quality images it produces compared to other image extension types, it maybe better for #media-processing your question though buddy as I don't really have experience in that field.
I only know this due to some digital art I produced in the past π
except function not working here
it is not creating channel if
channel is not there
can u show the code before that
@eternal fox
okok hmm
if member.guild.id == 997901679657754704:
welcome_channel = client.get_channel(channel id)
await welcome_channel.send(f':DiscordDesigns1: | Welcome to Discord Designs {member.mention}!')
π i'll take some!
a couple of unnecessary imports
Rate limits? Well, you just gotta use this event
@tasks.loop(seconds=30.0)
async def my_background_task():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching,name="Discord Designs"))
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching,name="Orders!"))
hey can you help?
i'll try
and I assure you'll be ratelimited
well it's there
do print("var", var)
Where?
or is that not in your code
the site package has print "var", var
I suppose the site package db has some issues
with python versions
I didn't understand
@real grail works π€·ββοΈ
I already installed db
but it uses python2
...
I have no idea where that package came from
!pypi db
never heard of it
0-0
"for Humans" well thanks bro
looks super sus
should i go full slash commands or still keep normal commands
the latest version is from 2014
hehe
please don't use that package
Ugh
"the updooter"
what even is this
lol bottom right
I do want a better computer
Go for it
lol
also a faster internet
I saw a tiktok that said we can have internet faster than light speed with some atomshit that reacts to the change of another atom faster than light speed
I'm gonna do that shit
Ah good old tik tok. π
valid source
or maybe we just need a smarter daniπ
"i saw a tiktok"
awaiting an async function is non blocking right 
tiktok sucks all bs there
please capitalize my name, I find this very disrespectful
even if there are blocking things inside?
kek
replace dani
no it's blocking
so no one would be able to use the bot until the await is done?
"nobody of you"
Imma leave
use loop.run_in_executor for blocking stuff
π
the command especially
fat W
it will queue up
does await just mean
anything past me wont happen until im done
??
that defeats the purpose of async doesn't itπΏ
no that's the exact opposite
it means u wait till i am done others can do their stuff and u will get what u asked me to do once i am done with it
would it work just to put the whole function in
thread.start()```
so its kinda like a child async?
basically does stuff without interfering and blocking others doing the same task
or does every blocking thing have to be done like that
I wouldn't really suggest using threading module when in discord.py