#discord-bots
1 messages · Page 664 of 1
dms closed
is it ok to use subprocesses for bot commands?
it gets irritating dealing with 3-4 people at once lol
i want, on a certain channel, the bot to ban texts... only images are allowed. if the user sends a text, the message will be deleted. how can i do this?
check this out
my eyes
where is ur .replit file
make a .replit named file
and add this
language = "python"
run = "python main.py"
replace os.getenv line with:
client.run(os.environ["test"])
i am sorry unable to uderstand
not required
ig its req in replit?
I use replit and never heard of doing that once
okk
so how u run it?
do slash commands exist in nextcord?
click on the run button
okay in the test file i had written token and copied my bot token and after running that my bot is still offline
hmm
file?
or env var?
its a file
is it ok to use subprocesses for bot commands?
And don't forget that please
lol
indentation
indents too
Same for the if statement above
lol
Lmao
so what should i do now
make an env variable
😆
what do you mean
there is a lock button on left side
add ur token there
Im new to discord bot programing and im tryin to get the bot to respond to the message from one channel to another and this is what i have got
async def on_message(message):
channel1 = ["📃・central"]
channel2 = ["📃・central-registos"]
if message.author == client.user:
return
if str(message.channel) in channel1:
await message.channel.send("a") ```
i have only made it to the point where he responds to me in the same channel, and the "a" s only for the test, and the channel1 is the one to cause the event and the channel2 is where i want it to respond
PLS DM ME IFF U CAN HELP
i was creating .env but it was showing an error
token = input("Token: ")```
Is this visible on replit?
yes
secret tab ryt ??
yes
you can have the token as an environment variable
that tab asked key and value
I know exactly what video your watching for that @cedar fern
Or.
freecodecamp 😁
add a name in key and ur bot token in value
w8
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
really u wanted to blur ur imports?
and call it by
client.run(os.environ["TOKEN"])
@sullen sedge You can still read them xD
why not, I have around 25 imports lol
yep
yes
cuz why not
import requests 
is it ok to use subprocesses for bot commands?
my question not answered ;-;
It's online
lolol
oauth link?
i feel like using dark mode now
now what should i do
this
and fix your indents
and a typo if message.author == client.user
Eevee you wanna gimme a hand real quick?
Im new to discord bot programing and im tryin to get the bot to respond to the message from one channel to another and this is what i have got
async def on_message(message):
channel1 = ["📃・central"]
channel2 = ["📃・central-registos"]
if message.author == client.user:
return
if str(message.channel) in channel1:
await message.channel.send("a") ```
i have only made it to the point where he responds to me in the same channel, and the "a" s only for the test, and the channel1 is the one to cause the event and the channel2 is where i want it to respond
PLS DM ME IFF U CAN HELP
Im having trouble getting my bot to role change people
well i am new to python will you tell me what indent is
@astral cobalt what's up
and how to fix that
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
the spacing, for example do !indent
I love spamming big tags
@maiden fable Still having trouble to get the bot to change roles @client.command() async def element(ctx, member : discord.Member, role : discord.Role): await member.add_roles(role)
^
indents are the number of tabs
That should work
okay
can you get the channel that way?
code?
so whats the problem of my indents
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 24, in element
await member.add_roles("Air")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'```
Oh sweet
events cant be inside other events
Ah, u should either provide it a role id or mention the role
i think so, at least its working rn
I pass in the role as an arg dont i?
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
Ngl I am confused whom to help and whom to not 😬
so i should do title="Name" instead of just name?
Yea
name="whatever"
ohk
What? embed constructor doesn't have any name kwarg?
Ah u talking about field
!d discord.Embed.add_field
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
That code doesent work @maiden fable
so i can do it name="Name" and stuff like that right
Okay... How r u invoking the command
Sure
there was an error in the fields
*element Andrew Air
Do u know how to copy the role id?
async def element(ctx, member : discord.Member, role : discord.Role):
await member.add_roles(role)```
Nvm
thx sooo much eevee and hunting the grinch
!d discord.ext.commands.RoleConverter
class discord.ext.commands.RoleConverter(*args, **kwargs)```
Converts to a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").
All lookups are via the local guild. If in a DM context, the converter raises [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") exception.
The lookup strategy is as follows (in order)...
Use this (:
commands.RoleConverter().convert(role)
Or something I don't remember lemme see
!d disnake.ext.commands.RoleConverter better
instead of what?
won't typehinting work tho?
Isn't working for some reason

^^^
does nextcord have slash commands?
@fair axle I dont think so
Nvm
BTW @visual island there's a possibility they flagged my bot ¯_(ツ)_/¯
@maiden fable Ignoring exception in command element: Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "main.py", line 24, in element await member.add_roles(role) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles await req(guild_id, user_id, role.id, reason=reason) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request raise Forbidden(r, data) discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Your bot doesn't have the perms to add roles
(:
I need help to make the bot respond in a specific channel, my goal is to register every mensage sent from One channel INTO another channel
How do you get what role a person has?
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
so if I want to find if a person has a specific role would the best way to do that is to find all there roles and see if it contains the specific role I want?
how do i make the bot to dm a interaction user when he uses a buuton?
inter.author.send
property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.name "discord.User.name")
when i send my first message on the server, the bot counts the xp but after that it doesnt count xp for the user
maybe, because of the trust & safety probably?
Idk, they don't tell the reason, neither do they tell if it's flagged or not ¯_(ツ)_/¯
But yea, that's a possibility
utils is not defined? but im importing the lobaray
when i send my first message on the server, the bot counts the xp but after that it doesnt count xp for the user
How do i set the bot to send a mensage on to a specific channel?
my bot its off why??
I rly need help, im trying to do it for a few hours
!d discord.abc.Messageable.send @leaden cargo
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Hm
sad
^
yes it works thank you I was stupid this is the first time
How can i aply it?
Like how can i praticly define where i have to out the channel só ir sends ir there?
Do you want to send it where the command was used in
No
Just do
channel = bot.get_channel(channel ID)
And then send the mensagem right?
get_channel(id, /)```
Returns a channel or thread with the given ID.
Alright Imma test it out!
using json?
what?
were you using json?
Thx for the help guys!
you want a command to have aliases?
what is aliases
like if prefix is ?
Doing ?p or doing ?profile will call the same command
await member.add_roles(role) Can I pass a string to this?
string for what?
adding a role to somone
Different names for a single command
you need the role object
you can get the role object with the name, yes.
yes
How do I get a role object?
@bot.command(aliases=["what you want it as"}```
with the name?
oo ok
async def element(ctx):
member = ctx.message.author
role = "Air"
await member.add_roles(role)``` I have this but it fails when I do
don't use that bracket
use [ and ]
@client.command()
async def element(ctx):
member = ctx.author
role = discord.utils.get(ctx.guild.roles, name="Air")
await member.add_roles(role)```
yes
THANKS
YOUR WELCOME
And how do I check if a member has a certain role?
you mean if he has role x, he can use a command otherwise he can't?
yeah
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
use that instead of @client.command()
@commands.has_role("name")
No, use it as a command decorator
so use both
Does it matter which one goes first
put @client.command() first
it really doesn’t but that’s ok ig.
yeah it doesn't but this is generally put first.
And if the user doesent have that role it will error, how should I catch that? or should I even catch it?
stay consistent for readability sake ofc
Put it in your error handler
you cant add a string to a member
do you want to catch it?
it was already said
how can i got problem here, idk
Wait I put an error where?
!d discord.ext.commands.MissingRole This is the error that comes from a check failure of @commands.has_role
exception discord.ext.commands.MissingRole(missing_role)```
Exception raised when the command invoker lacks a role to run a command.
This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
New in version 1.1.
thanks, i put it in here cause i dont like the weather noti
Do you use bare try and excepts
no
i.e
try:
#something
except:
#something else```
okay
So I need to make a seperate error handler that will catch errors from any of my calls?
do you already have an error handler?
No
Simple Error Handling for ext.commands - discord.py - error_handler.py
This is the one that dpy recommends
You can either do it for each command, or do an on_command_error event
@bot.command(aliases ={ 'p', 'profile'})
@commands.cooldown(1, 1, commands.BucketType.user)
async def profile(ctx):
userid = str(ctx.author.id)
whats wrong
i ave a list of string
oo the bracket
wrong bracket
youre using set
So if I wanted to do it for just this command would I use a try exepct and inside the try do @commands.has_role("Air")
huh
No bro
@bot.command()
@commands.has_role("role name")
async def...```
Its a decorator that is written after command decorator
Okay thats what I have but im just confused on how to catch that error inside the def
@bot.command(aliases =['p', 'profile'])
@commands.cooldown(1, 1, commands.BucketType.user)
async def profile(ctx):
userid = str(ctx.author.id)
You can't
You can't have a alias and a command name as same
That goes for every command
oo
so what do i do
i cant define a function without name
🤣
So if the user doesent have the role with @client.command() @commands.has_role("Air") I cant send a value back to discord saying "Permission not allowed"
remove profile from the aliases
Would I have to check inside the definition instead of having the decerator
no use an error handler
oo ok
The function name is the main command name
Tylerr sent a link on it above
Else there is a name kwarg too
can i run 2 bot in one python file
okok
yes but why
where can I get invite to disnake server?
Can but not recommended
Dm
what?
so i can host 2 bot in one server
ty
ah
Wait server
;-;
Depends on the server
;--;
hmm?
i dont got it but ok
Bot1 = commands.Bot()
Bot2 = commands.Bot()
...
asyncio.create_task(Bot1.start())
Bot2.run()
ohh
Its not recommended tho
why is there so many github repos with name "disnake"
Thats really cool and funny lol
I can't find the original one
its like i say hello ''hello"
bot says = hello @tacit horizon
@bot.group()
@commands.cooldown(1, 1, commands.BucketType.user)
@bot.command(aliases = ['craft 1'])
async def craft(ctx):
await ctx.send('hello world')
I just found that 😅 , took me a while. Thx
youre registering it twice with .group() and .command()
help ! ;-;

no, remove the@bot.command() in the craft function
does disnake support slash commands in cogs?
!d discord.Member.mention
property mention: str```
Returns a string that allows you to mention the member.
Very clean lol
so how will it looks like
@bot.group()
@commands.cooldown(1, 1, commands.BucketType.user)
@bot.command(aliases = ['craft 1'])
async def craft(ctx):
await ctx.send('hello world')
```from this
@bot.group()
@commands.cooldown(1, 1, commands.BucketType.user)
(aliases = ['craft 1'])
async def craft(ctx):
await ctx.send('hello world')
```like this?
=.=
@commands.has_role("Air") Throws an error if the user doesent have the right role, im confused on how to catch it
now move that aliases thing to be inside bot.group deco
ok
!d discord.ext.commands.CheckFailure
exception discord.ext.commands.CheckFailure(message=None, *args)```
Exception raised when the predicates in [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks") have failed.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
lemme try
or is it MissingRole cant remember
but that will show hello world all the time
when i use craft blah blah
i think its MissingRole
you cant have space in command names/aliases
oh yeah
you can use groups or args to have spaces in commands
is there any way to catch TimeoutError in the on_command_error event?
so i need to do craft and craft 1 two different thing?
but they function the same way tho
@visual island How do I use the exception discord.ext.commands.CheckFailure(message=None, *args). Where would I put it?
is this error handler
yeah
@bot.event
async def on_command_error(ctx):
if errortype:
await ctx.send(show error)
else:
raise error
this is how i do error handler
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'Commannd is on cooldown. You can use it in **{round(error.retry_after, 2)}** seconds')
elif isinstance(error, commands.CommandNotFound):
await ctx.send('ERROR 404 command not found')
else:
raise error
```this is the ori code if u wan for sample
So I would have this function after my client.command() and if my client.command() fails it will go to this error function?
@bot.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRole):
...
it's MissingRole not CheckFailure mb
just change the blahblah in commands.blahblah
it says bot is not defined
it's the bot instance, you probably named it client or something
u use client = discord.client() or bot = bot.commands()
how do i make the bot send a message when a user uses a buttons but the message should not be replying
@visual island It still throws the error File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1646, in predicate raise MissingRole(item) discord.ext.commands.errors.MissingRole: Role 'Air' is required to run this command.
Just copied what you sent me ```@client.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'Commannd is on cooldown. You can use it in {round(error.retry_after, 2)} seconds')
elif isinstance(error, commands.CommandNotFound):
await ctx.send('ERROR 404 command not found')
else:
raise error
do this
Thank you!
Ayo
Does anyone know how i can run an async function using a lambda?
Im trying to make a queue for my bot
hmm?
lambda _: await my_async()
@bot.command(aliases = ['i', 'inventory'])
@commands.cooldown(1, 1, commands.BucketType.user)
async def inv(ctx):
userid = str(ctx.author.id)
res1 = ''
for item in items['mobdrop']:
emoji = discord.utils.get(bot.emojis, name = item)
value = db[userid + item]
if value > 0:
res1 += f"{emoji}{item}: {value}\n"
res2 = ''
for item in items['misc']:
emoji = discord.utils.get(bot.emojis, name = item)
value = db[userid + item]
if value > 0:
res2 += f"{emoji}{item}: {value}\n"
res3 = ''
for item in items['illegal']:
emoji = discord.utils.get(bot.emojis, name = item)
value = db[userid + item]
if value > 0:
res3 += f"{emoji}{item}: {value}\n"
res4 = ''
for armor in armors:
value = db[userid + armor]
if value == 0:
res4 += f'No {armor}\n'
if value == 1:
res4 += f'pog_{armor}\n'
if value == 2:
res4 += f'iron_{armor}\n'
if value == 3:
res4 += f'diamond_{armor}\n'
if value == 4:
res4 += f'meaty_wooly_diamond_{armor}\n'
if value == 5:
res4 += f'shiny_meaty_wooly_diamond_{armor}\n'
if value == 6:
res4 += f'shiny_meaty_wooly_netherite_{armor}\n'
if value == 7:
res4 += f'more_shiny_meaty_wooly_netherite_{armor}\n'
if value == 69:
res4 += 'beefy_sword'
if res1 == '':
res1 = 'None'
if res2 == '':
res2 = 'None'
if res3 == '':
res3 = 'None'
if res4 == '':
res4 = 'None'
embed = discord.Embed(
title = f"**{ctx.author.name}**'s profile",
color = discord.Color.blue()
)
embed.add_field(name = 'items',value = res1, inline=True)
embed.add_field(name = 'misc',value = res2, inline=True)
embed.add_field(name = 'illegal',value= res3, inline=True)
embed.add_field(name = 'armors & tools',value= res4, inline=True)
await ctx.send(embed=embed)
why is there Nonecobble: 1
erros this : 'await' outside async function
3 sec is too fast
im using the lamba as an after function
!d asyncio.create_task use this
asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
help
you can use while True loop or tasks.loop
it should be :cobble_emoji:cobble: 1 but the emoji returns None so it displays as Nonecobble: 1
oooo
thanks
hmm, why do you need create_task?
@bot.command()
async def g(ctx):
user = ctx.author.id
with open("ids.txt", "r") as f:
if user in f:
await ctx.send('hm')
else:
with open("ids.txt", "a") as f:
f.writelines(f'{user}\n')
await ctx.send('gg')```
it always replies with gg even though the txt file has the author's id
you need to read the file
I'm currently host my discord bot on replit, and it's working.
cool 
use asyncio.Queue
!d asyncio.Queue
class asyncio.Queue(maxsize=0)```
A first in, first out (FIFO) queue.
If *maxsize* is less than or equal to zero, the queue size is infinite. If it is an integer greater than `0`, then `await put()` blocks when the queue reaches *maxsize* until an item is removed by [`get()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.get "asyncio.Queue.get").
Unlike the standard library threading [`queue`](https://docs.python.org/3/library/queue.html#module-queue "queue: A synchronized queue class."), the size of the queue is always known and can be returned by calling the [`qsize()`](https://docs.python.org/3/library/asyncio-queue.html#asyncio.Queue.qsize "asyncio.Queue.qsize") method.
This class is [not thread safe](https://docs.python.org/3/library/asyncio-dev.html#asyncio-multithreading).
Not really
inside the if statement?
Replit's hosting isn't consistent at all and replit isn't even made for hosting
@commands.has_role(role) Is there a way to include multiple roles? If user has this role OR this role OR this role
open("ids.txt", "r").read() + f"\n{ctx.author.id}"
commands.has_any_role
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
commands.has_any_roles("role 1", "role 2", "role 3")
why is it sending the message in the same channel iff i put another channel's id?
await message.channel.send( content )```
no i mean in the if function like
if:
open("ids.txt", "r").read() + f"\n{ctx.author.id}"```
?
or
```py
open("ids.txt", "r").read() + f"\n{ctx.author.id}"
if:```
The best way to change tasks is to use a task loop that changes status after a minute
Because if you change statuses too fast you will get ratelimited
I dont get the use of Queue there
What kind of queue do they want then?
Sorry if I didn't understand the question
yes, use f.read() in the id statement
they want to run a coroutine without being inside an async function, that's all
Well you can't run coroutines in a non async function
and you can use asyncio.Queue to queue stuff
@bot.command()
async def g(ctx):
user = str(ctx.author.id)
with open("ids.txt", "r") as f:
if user in f.read():
await ctx.send('hm')
else:
with open("ids.txt", "w") as f:
f.write(f"{open('ids.txt').read()}\n{ctx.author.id}")
await ctx.send('gg') ```
This?
^^ @untold token
why is it sending the message in the same channel iff i put another channel's id?
await message.channel.send( content )```
asyncio.Queue is not the thing for running coroutines, its just for handling the Tasks queue
from itertools import cycle
statuses = cycle([...]) # cycles through the list of statuses
@tasks.loop(minutes=12)
async def status_change():
await bot.wait_until_ready() # make sure the bot is ready
await bot.change_presence(activity=discord.Game(next(statuses))) # task that changes status
status_change.start() # start the task
how do I connect a google drive api with my discord bot make changes in a file when a certain command is used?
that's a background task,
it creates a task that runs asynchronous
Google it.
Whats the best way to make a list of commands the I can do *help with? Is it to create it by hand or have a text file or is there some built in function for that already?
if they want to run synchronous functions in asynchronous code they would need to use executor
loop.run_in_executor
did all it shows how to upload data
I don't know, I never use google drive.
but yea, they want to run a coroutine in sync func not sync/blocking function in an async
any other cloud storage api?
!d asyncio.loop.run_in_executor
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
Yeah
MongoDB.
async def help(ctx):
for command in self.client.commands:
helptext+=f"{command}\n"
await ctx.send(helptext)``` Anyone know why thus wont work? ```The command help is already an existing command or alias.
Cloud storage API??
help_command = None in your bot's constructor
its actually a database
Add Bot.remove_command("help").
That's bad practice, you should put help_command=None while creating the bot object
Indentation please.
Hm yeah
Look at indentation
unindent the async def and the last line
Yes
and don't await the .start()
@visual island ```@client.command(name="help", description="Returns all commands available")
async def help(ctx):
print("In here")
helptext = " "
for command in self.client.commands:
helptext+=f"{command}\n"
print(helptext)
await ctx.send(helptext)``` Do you know why this wont get ony of the commands?
pinging the wrong guy lol
I have a command where my bot get images and send them. I do not know whether they have swears or not. I wanted to not send images with swears. I could extract text from the image and then check it for swears. Is there any module to extract text from images?
Note: I am using GitHub for storing the code and Heroku for hosting the bot.
Oops lol
it's an awaitable
!d discord.ext.tasks.Loop.start
start(*args, **kwargs)```
Starts the internal task in the event loop.
TypeError: send() takes from 1 to 2 positional arguments but 3 were given
iirc
whats that error?
yeah asyncio.Task is awaitable
it takes from this lineawait message.channel.send(content, author)
when i set it with content only it works, but when i add author it doesnt
The docs confused me
do you mean no commands are displayed?
and i have done
author = str(message.author)```
how can I change user's nickname on specific server?
i tried without the str first and then with it
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
I have a command where my bot get images and send them. I do not know whether they have swears or not. I wanted to not send images with swears. I could extract text from the image and then check it for swears. Is there any module to extract text from images?
Note: I am using GitHub for storing the code and Heroku for hosting the bot.
thanks
@visual island Yeah non of my commands are being displayed
!f-string
» sql-fstring
» f-strings
I dont think im getthing them right
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
is this how you make a slash commands with disnake? ```py
@commands.slash_command(name="test")
async def _test(self, ctx):
await ctx.send("hi")
help pls?
firstly, have you defined self?
no, I only asked
Thank you
you dont need self.client.commands
I dont?
client.commands is enough
Gotchu I see
as youre not in cog
hm
dont await last line
hi
Could you send the full code?
hi icy
put it in an async func or inside on ready
but i dont think
u need to await tasks to start them
not sure though
yeah you don't
lmao
you probably missed a bracket/smth
Is there a way to add a line in between team1 & team2 and the Makes lobby fields?
like a blank line
nice

hello Kayle
hello dekriel
Would u happen to know Kayle
U know everything I swear 
finally
someone called me Dekriel
yes
import tasks
as well
import ext.commands
^
||imagine not indenting it||
For some reason I can't seem to get user.avatar_url via discord.User it says 'str' object has no attribute to 'avatar_url` any help?
what's user
Yeah I've tried that
get the user object first
Doesn't work
show code
I use the userID so yeah
you probably forgot to define user or maybe you got it wrong
!d discord.User.avatar
property avatar: Optional[discord.asset.Asset]```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.display_avatar "discord.User.display_avatar").
https://stackoverflow.com/questions/59872089/how-to-get-a-mentioned-users-avatar-url-with-discord-py some link here 🙂
show code
That would only be users in the guild I want users outside the guild too
I mean you can try this but he has the ID I think
that's impossible
it isnt
but
!d discord.User lol
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
you cant mention users in other guilds 😭
he has id ig
ok 😭
!d discord.ext.commands.Bot.get_user <=
get_user(id, /)```
Returns a user with the given ID.
ok 😭
@forest spear show me your code
It's not impossible I have the code in my avatar command too
Here's the code ```py
@client.command()
async def modlogs(ctx, *,user: discord.User = None):
if user == None:
user = ctx.author
yes = str(user.id)
data1 = mod.fetch({"id":yes})
if data1.items:
embed = discord.Embed(title="Quotes",color=0x00FFFF,timestamp=ctx.message.created_at)
for item in data1.items:
yes = item['action']
yes1 = item['time']
yes2 = item['reason']
name = item['mod']
user = item['name']
embed.add_field(name=f"{yes} | {yes1}",value=f"Responsible Moderator: {name}\nReason: {yes2}",inline=True)
embed.set_footer(text=f"Requested by {ctx.author}", icon_url=ctx.author.avatar_url)
embed.set_author(name=f"{user}", icon_url=f"{user.avatar}")
await ctx.send(embed=embed)
if not data1.items:
await ctx.send("Couldn't find any saved quotes from the user")
hmm
where's the error again
is that where the error was? aight
try making it not a string
I mean it depends what mod is
user.avatar only, not quotes
Tries .format too and in variable but it didn't work
^^
https://stackoverflow.com/questions/59872089/how-to-get-a-mentioned-users-avatar-url-with-discord-py maybe this ;-; or not
😭 I like crying
mentioned
sorry Kayle 😭
user.avatar_url
If it is dpy 1.7.3
user.avatar.url
If it is dpy 2.0
but
user.avatar will work fine in embeds
Sorry still doesn't work
that's what it says in the stack overflow answer
show the error
userAvatar = member.avatar_url 😭
No, user.avatar returns an asset object
and icon_url takes an url which is a string
kayle vs ! a
mine works without the url attr though
I have a command where my bot get images and send them. I do not know whether they have swears or not. I wanted to not send images with swears. I could extract text from the image and then check it for swears. Is there any module to extract text from images?
Note: I am using GitHub for storing the code and Heroku for hosting the bot.
embed.set_author(name=f"{user}", icon_url={user.avatar_url})
AttributeError: 'str' object has no attribute 'avatar_url'
!d discord.Member.avatar
try getting the user, then use that attribute
The exact same thing works fine in my avatar command but doesn't work in my modlogs
what is the { for
client.get_user?
Huh
yes
Doesn't work either lol
!d discord.User.avatar @untold token
property avatar: Optional[discord.asset.Asset]```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/master/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.display_avatar "discord.User.display_avatar").
url attr is separate
.
!d discord.Asset.url <=
property url: str```
Returns the underlying URL of the asset.
yes
icon_url takes an url though
I even tried uninstalling discord.py and reinstalling it but idk it doesn't work
It doesn't work I've tried it before
AttributeError: 'str' object has no attribute 'avatar_url' is it to do with the str?
I'm a bit slow
user is an str?
The str is optional as written in docs so idk why it's even giving me an error
you're redefining user to become item['name']
which is a string
how do i persistent a view where i am using ctx
class view(discord.ui.View):
def __init__(self,ctx):
super().__init__(timeout=None)
self.ctx = ctx
self.bot = ctx.bot
```i need ctx in this view but i also want to persistent it
i am persistenting in on_ready
Omg
o
I hate it when that happens
Thank you genius person
icy saves the day ^_^
this is why you dont make params/vars with the same name
lol I read your code 20 times
Dumb me
then I realized that
icy fast reader
just use command.Context in the class args
I've been at this for well over an hour thank you icy
icy go brrr
Hm
I'm still making my IDE, maybe I can use dpy on there someday
working on terminal 🙂
Oo, any repo?
wow nice
i dont get it
Sup hunter
not yet
Hi
yo anyone know a fix?
AttributeError: 'Message' object has no attribute 'user' ```py
async def on_reaction_add(reaction, user):
if reaction.emoji == "💸":
if user == bot.user:
return
for i in range(0,len(Json_Items)): #It doesn't exist
for x in Json_Items[i]:
if int(x) == int(user.id):
if Json_Items[i][x]['cBool'] == True or Json_Items[i][x]['vBool'] == True:
message = reaction.message
await message.remove_reaction("💸", message.user)
else:
Json_Items[i][x]['Pbool'] = True
Json_Items[i][x]['bads_variable'] = int((Json_Items[i][x]['bads_variable']) + 1)
json.dump(Json_Items, open("./all_user_rep.json", "w"), indent=1)```
huntering the grinch
i'll call you grinch hunter from now
i have a subclass of context tho
view(commands.Context)
What is the best current method for a Discord bot to play an audio file from local system or otherwise?
use that then
ffmpeg
Maybe that's where you get music
message.author?
You would need to see ffmpeg to do that
whenever you guys start typing I get scared
why
phew I was correct
is FFMPEG the only current method?
idk
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "main.py", line 172, in on_ready
self.add_view(supportmenu(Context), message_id=918495237972840449)
File "/home/runner/core/buttons.py", line 65, in __init__
self.bot = ctx.bot
AttributeError: type object 'Context' has no attribute 'bot'
mk
no......maybe...
show code 🙏
it would be message.author
yes, you need ffmpeg to play something on vc
!d discord.Message.remove_reaction
await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
If the reaction is not your own (i.e. `member` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.
The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
ugh, many reasons why I dont use a subclassed context
thanks guys 🙂
i used that only lol
ik but sometimes.....
If I call @commands.has_role(role) two different times and I want to have two different error handles for each one how do I differentiate?
no idea how to solve your error, sorry lmao
errr...code
I do have error code but my error code has if isinstance(error, commands.MissingRole):
ok
And I want two different prints depending on which def the error is in
I meant Destro but ok
Also icon_url takes an url not an Asset object
well...I think there is a one to sense an command
!d discord.Embed.set_footer
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
@astral cobalt https://stackoverflow.com/questions/65977824/how-can-i-know-the-command-used-discord-py
I am trying to make a errorhandling for my Discord.py, how do I know what command was used for the error to pop up?
@bot.event
async def on_command_error(ctx, error):
print("error: ",...
you can try this and use an error handler for it
Thanks
ctx.command.name returns the command name
how'd this work then?
grinch hunter doing this 🙂
???
i need to make a command that stores a user's information in a json file like this:
userid {
nick: string
about me: string
years old: int
}
``` how can i do?
nothing I was speaking nonsense
display_avatar returns url, because icon_url doesn't take an asset object
using JSON as a db 🙂 or not
o
my bad then
!d discord.Member.display_avatar
property display_avatar: discord.asset.Asset```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
{
"name": "something"
"age": "something else"
}
i dont know use databases
you can create different json files for different things
nice phone
async def update_data():
await client.wait_until_ready()
while not client.is_closed():
with open("disc_text.txt", "w") as fin:
fin.write("hi")
await asyncio.sleep(5)
hi, im trying to write data to a file, but it isnt writing for some reason. i dont want to use a database since its only for a small server
thanks
yes but this would make the file stay more heavy
....heavy?
why?
Its not a database
use mongo, its way easier and its like json
Yeah
there is any tutorial?
Json is format that used API/ different programming languages/ servers and machines to communicate and send data in a format that anyone can read, it's an universal format used for communication and transferring of data
Json isn't meant to be used a database
no, but its easy to setup
and if you use it, you will deal with more problems than ever
you could watch a tutorial for the functions (pymongo, a wrapper for it) though
bruh
what are the syntaxes that i can use?
What bruh
Using synchronous modules / libraries in asynchronous code is a very very bad idea
what syntax
isnt motor literally pymongo but async
Yeah it is
hm
i was typing something else
yo anyone know a fix?
AttributeError: 'Message' object has no attribute 'user' ```py
async def on_reaction_add(reaction, user):
if reaction.emoji == ":money_with_wings:":
if user == bot.user:
return
for i in range(0,len(Json_Items)): #It doesn't exist
for x in Json_Items[i]:
if int(x) == int(user.id):
if Json_Items[i][x]['cBool'] == True or Json_Items[i][x]['vBool'] == True:
message = reaction.message
await message.remove_reaction(":money_with_wings:", reaction.user)
else:
Json_Items[i][x]['Pbool'] = True
Json_Items[i][x]['bads_variable'] = int((Json_Items[i][x]['bads_variable']) + 1)
json.dump(Json_Items, open("./all_user_rep.json", "w"), indent=1)```
I need the reaction of the user to be removed
i didnt wanna get muted again though so i sent hm 🙂
I hate reactions man
What is the best way to track or check a status like whether or not the bot is already in a voice Channel? Should I create a variable to track that or is there some way using built-in Discord attributes to determine that?
is your error in the if user == bot.user: line ?
its await message.remove_reaction(":money_with_wings:", reaction.user)
i stream webradio to voicechannel it works but i usally has to restart bot to get it even to join vc , sometimes it cuts off n refuse to join if not restart bot any cache issue or whats going on
because it doesn't have a user argument, only a member argument
Does it work with await reaction.remove(reaction.user) ?
Hey, how do I make it so the index.py file reads the token I put into the config.json file?
by reading the json file
How do I make it do that?
import disnake
import time
import random
client = disnake.Client()
@client.event
async def on_ready():
print(f"Attention! {client.user} has been successfully accessed!")
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hola!')
client.run(token)
That's my code as of rn
google python3 how read file
it is cause reaction doesn't have the arugment user
is there any way to check time spent on voice channel of a particular user?
@modest plover as i said google python3 how read file
no, it is because remove_reaction that doesn't have any user argument
but reaction.remove, yes
is the sourcecode of the python bot official? i want to do an eval command
nvm i found it
why i dont get the error message on discord (insted i get an error on bot logs) ```py
@client.command()
@commands.has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member, *, reason = None):
await member.kick(reason = reason)
await ctx.channel.send(f'{member.mention} has been kicked by {ctx.message.author.mention} for reason of: {reason}!')
@kick.error
async def kick_error(self, ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send("You don't have permission to kick members.")
idle-09 is my alt with no perms and the first account is my main
thats the error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: kick_error() missing 1 required positional argument: 'error'
why self...?
remove self
from discord.ext import commands, tasks
from itertools import cycle
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils.manage_commands import create_choice, create_option
class Example(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command
slash = SlashCommand(client, sync_commands=True)
@slash.slash(
name="ping"
description="just shows ping"
async def ping(self, ctx:SlashContext):
await ctx.send(f'Pong! {round(self.client.latency * 1000)}ms')
def setup(client):
client.add_cog(Example(client))```
shows error
@commands.command should not be there , client variable is undefined at the place you defined slash var
just use a fork
is there a way to make the bot count all the channels inside a category?
!d discord.CategoryChannel.channels
property channels: List[GuildChannelType]```
Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
oh alright
@tasks.loop(seconds=5)
async def send_webhooks(self):
await self.bot.wait_until_ready()
self.dispatcher_cog = self.bot.get_cog("Dispatcher")
async with self.batch_lock:
if self.logging_batch:
for webhook, embeds in self.logging_batch.items():
if embeds:
first_ten = embeds[:10]
print([i.title for i in first_ten])
try:
webhook_to_send = discord.Webhook.from_url(webhook, session=self.bot.session, bot_token=self.bot.http.token)
await webhook_to_send.send(embeds=first_ten, username=f"LogRack Logging", avatar_url=self.bot.user.avatar.url)
except discord.NotFound:
...
except Exception as e:
print(format_error(e))
self.logging_batch[webhook] = embeds[10:]
>>> ['A member just edited their message.', 'Message deleted']
its printing both embed but only sending the first one any reason for that?
yes because remove_reaction takes a reaction argument and a member argument not user
Weird...
idk whats happening its printing both embed but not sending them
i have this code in on_member_join
welcome_channel = client.get_guild(835982376961835079).get_channel(835982376961835082)
and it's not working, there's no error or anything, how can i fix it?
Can u print first_ten directly?
sec
@bot.command()
async def test(ctx):
guild = bot.get_guild(572697526851993602)
user = guild.get_member(496569071106523148)
await user.send(f'{ctx.author.id}')
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
the guild and user ID's are correct but still
How do uk it's not working?
I tried joining my alt and it's not sending anything on the channel
ID of the user is wrong
intents issue mb
Yea
either the user id is wrong , or you dont have member intents
there are 3 embeds but it only sent 2 [<discord.embeds.Embed object at 0x059896E8>, <discord.embeds.Embed object at 0x05989E38>, <discord.embeds.Embed object at 0x05989AD8>]
member intents?
!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 the Members and Presences intents, which are needed for events such as on_member 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.
it didnt print the msg delete
Okay...
So can u get the embed object of message delete embed?
!d discord.Embed.to_dict try doing this on the message delete embed
to_dict()```
Converts this embed object into a dict.
I tried this and i don't understand it won't work
@client.event
async def on_member_join(member):
print("joined!")
I tried to join my alt acc and it's sending any " joined! " message on the console
Hey, can someone help me with an error here?
it works properly if i do it alone like only triigger msg delete event
Not without the error
@slate swan same for ya
Weirdddd
Can u try removing the try except to see if there ain't any errors?
RuntimeError: Timeout context manager should be used inside a task
What is the reason for this? I could provide my code but its a bit confusing.
alr
By doing print("joined!"), you send a message to the console, not in the chat.
Lemme guess... Using Python 3.10?
thanks bhai
I know, and there's nothing
pretty sure yes
np
i tried sending it via bot without any error handler, same issue
And that's with aiohttp?
i tried create like a form on dm of a user:
await member.send('**NICK** | type ur ign.')
nick = await fpr.wait_for("message", check=check)
while len(nick.content) > 16 or len(nick.content) < 3 or ' ' in nick.content or special_characters in nick.content:
await member.send('**ERROR** | type ur ign correctly.')
nick = await fpr.wait_for("message", check=check)
else:
await member.edit(nick='[FPR] ' + nick.content)
pass
``` but the `member.edit` does not work... i would like that the bot edit user's name for {nick.content} in a specific guild... how can i do it?
Weird... @slate swan do u mind helping this guy?
Im not sure what aiohttp is
Nvm just show me the code which is causing the error
I already have the intents on
@maiden fable
from rustplus import RustSocket, CommandOptions, Command
from discord.ext import commands
import discord
import time
# Commands List: !pop, !zeit, !map(WIP)
TOKEN = 'x'
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
@client.event
async def on_ready():
print("Bot is up")
await main()
async def sendmaptochat():
event_channel = client.get_channel(917910425025261628)
await event_channel.send('hello')
async def main():
print("main() is running")
options = CommandOptions(prefix="!")
socket = RustSocket(x)
await socket.connect()
useless = await socket.getTime()
@socket.command
async def zeit(command: Command):
await socket.connect()
time1 = await socket.getTime()
await socket.sendTeamMessage(f"Current Time: {time1.time}")
await socket.disconnect()
@socket.command
async def pop(command: Command):
await socket.connect()
population = await socket.getInfo()
await socket.sendTeamMessage(f"Pop: {population.players} Queue: {population.queued_players}")
await socket.disconnect()
@socket.command
async def map(command: Command):
await socket.connect()
map1 = await socket.getMap(True, True, False)
map1.save("map.png")
time.sleep(5)
await sendmaptochat()
await socket.disconnect()
client.run(TOKEN)
Which line?
so essentially it all fails at the sendmaptochat function
Is that bad?
Very bad
Yea
Then im getting this error 'RuntimeWarning: coroutine 'RustSocket.connect' was never awaited
socket.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback'
the bot does not send the logs only for messages which got deleted right?
Does "except Exception as e:" work on python 3.5.3?
it does work if i just delete the msg
and not trigger other events
U can do all that in on ready
I don't know what that is
but in on_ready? 
from rustplus import RustSocket, CommandOptions, Command
from discord.ext import commands
import discord
import time
# Commands List: !pop, !zeit, !map(WIP)
TOKEN = 'x'
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents=intents)
options = CommandOptions(prefix="!")
socket = RustSocket(x)
@client.event
async def on_ready():
print("Bot is up")
await socket.connect()
useless = await socket.getTime()
async def sendmaptochat():
event_channel = client.get_channel(917910425025261628)
await event_channel.send('hello')
@socket.command
async def zeit(command: Command):
await socket.connect()
time1 = await socket.getTime()
await socket.sendTeamMessage(f"Current Time: {time1.time}")
await socket.disconnect()
@socket.command
async def pop(command: Command):
await socket.connect()
population = await socket.getInfo()
await socket.sendTeamMessage(f"Pop: {population.players} Queue: {population.queued_players}")
await socket.disconnect()
@socket.command
async def map(command: Command):
await socket.connect()
map1 = await socket.getMap(True, True, False)
map1.save("map.png")
time.sleep(5)
await sendmaptochat()
await socket.disconnect()
client.run(TOKEN)
alright this works so far, but I still get the same error
Hey @median cosmos!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
error in line 50 and line 27
line 50 is await sendmaptochat() and 27 the try to send "hello" in the channel
Why do you need one?
You could use cogs and just reload them without any downtime to the bot
@maiden fable Are you still here?
i dont understand how to use cogs
Sorry I died for a couple of minutes
all good?
so I have removed the main function but the problem remains
the goal is to upload a picture of the map.png to the discord
anything i could do?
how do you make the embed for delete message event?
sec ill show the code
@commands.command(hidden = True)
async def load(self, *, module: str):
try:
self.bot.load_extension(module)
except Exception as e:
await
self.bot.say('\N{PISTOL}')
await self.bot.say('{}: {}'.format(type(e).__name__, e))
else :
await self.bot.say('\N{OK HAND SIGN}')
@commands.command(hidden = True)
async def unload(self, *, module: str):
try:
self.bot.unload_extension(module)
except Exception as e:
await
self.bot.say('\N{PISTOL}')
await self.bot.say('{}: {}'.format(type(e).__name__, e))
else :
await self.bot.say('\N{OK HAND SIGN}')
@commands.command(name = 'reload', hidden = True)
async def _reload(self, *, module: str):
try:
self.bot.unload_extension(module)
self.bot.load_extension(module)
except Exception as e:
await
self.bot.say('\N{PISTOL}')
await self.bot.say('{}: {}'.format(type(e).__name__, e))
else :
await self.bot.say('\N{OK HAND SIGN}')
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 596, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 839, in exec_module
File "<frozen importlib._bootstrap_external>", line 976, in get_code
File "<frozen importlib._bootstrap_external>", line 906, in source_to_code
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/runner/FNCS-Scrims/cogs/commands.py", line 300
except Exception as e:
^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 72, in <module>
bot.load_extension(f"cogs.{file[:-3]}")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 653, in load_extension
self._load_from_module_spec(spec, name)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 599, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.commands' raised an error: SyntaxError: invalid syntax (commands.py, line 300)
async def save_append_log(self, record, *, embed):
async with self.batch_lock:
self.logging_batch[record.webhook].append(embed)
await save_logging(record, embed)
i have this code using pillow and it's not working, how can i fix this?
image_editable.text((94,475), title_name, (255, 255, 255), font=title_font)
image_editable.text((59,517), title_id, (255, 255, 255), font=title_font)
error
in _multiline_check
return split_character in text
TypeError: argument of type 'int' is not iterable
yo anyone know a fix?
AttributeError: 'Reaction' object has no attribute 'user' ```py
async def on_reaction_add(reaction, user):
if reaction.emoji == ":money_with_wings:":
if user == bot.user:
return
for i in range(0,len(Json_Items)): #It doesn't exist
for x in Json_Items[i]:
if int(x) == int(user.id):
if Json_Items[i][x]['cBool'] == True or Json_Items[i][x]['vBool'] == True:
message = reaction.message
await message.remove_reaction(":money_with_wings:", reaction.user)
else:
Json_Items[i][x]['Pbool'] = True
Json_Items[i][x]['bads_variable'] = int((Json_Items[i][x]['bads_variable']) + 1)
json.dump(Json_Items, open("./all_user_rep.json", "w"), indent=1)```
I need the reaction of the user to be removed
unable to figure out the problem bro , sorry
why do you need reaction.user , you already have a user object there...
help? ```py
@client.command
@commands.has_permissions(administrator=True)
async def restart(ctx):
shutdown_embed = discord.Embed(title='Bot Update', description='I am now Restarting. See you later. BYE! :slight_smile:', color=0x8ee6dd)
await ctx.channel.send(embed=shutdown_embed)
await client.logout()
@restart.error
async def restart_error(ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send("This command is OWNER only. You are not allowed to use this. Try not to execute it another time.")
command()
U didn't call it lol
.command()
oh fuc
Why not using @commands.is_owner()
???
Commands is_owner is for person who made the bot
is a privat bot
Yeah
Hi
Oh
Hi
i have this code using pillow and it's not working, how can i fix this?
image_editable.text((94,475), title_name, (255, 255, 255), font=title_font)
image_editable.text((59,517), title_id, (255, 255, 255), font=title_font)
error
in _multiline_check
return split_character in text
TypeError: argument of type 'int' is not iterable
um
How to make a translator
you are genius
WDYM?
thanks
I wanna make one
A language translator?
Or you just wanna implement that feature in your bot?
Na its for secret language
Secret language?
Like 1=a b=2 c=3
bruh
Sir
after i did restart he shutdown and never comeback
Yes
I failed to understand
Aa
And it's not related to #discord-bots
K
How can I reconstruct this function to make the bot not be hung up with the while True: loop?
@called_every_five_minutes.before_loop
async def before():
await bot.wait_until_ready()
await asyncio.sleep(5)
print("Checking the time.")
while True:
t = time.localtime()
current_minute = time.strftime("%M", t)
if int(current_minute) % 5 == 0:
print("It is now a 5 minute interval. Starting loop.")
break
else:
print("Not a 5 minute interval.")```
Do u play anigame
no
K
I am not interested inn gaming at all
Do u know how to make one?
Make one what?
Make games
Don't understand how u plan to do it because there are 26 letters and 10 unique numbers
I learned lua but then got bored
A language...
K
@maiden fable Do you have any idea how I could fix the problem?
Sorry, that error came with another module for me... Try opening a help channel
A language for 2d games
pygame would be better I believe
Yea
K
Or arcade, but this aint the correct channel
?
#game-development can help u with this
K
how can i fix this error ?
There ain't a file with that name on that path
Repl it??
File "/home/runner/MS-Bot-1/cogs/config.py", line 25, in Config
credentials = service_account.Credentials.from_service_account_file(secret_file, scopes=scopes)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/google/oauth2/service_account.py", line 238, in from_service_account_file
info, signer = _service_account_info.from_filename(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/google/auth/_service_account_info.py", line 72, in from_filename
with io.open(filename, "r", encoding="utf-8") as json_file:
FileNotFoundError: [Errno 2] No such file or directory: '/home/runner/MS-Bot-1/config/credentials.json'```
yes
K
how can i add the file in that path ?
Whats this?
the error im getting
The file isn't there in the config folder bruv
i have this code using pillow and it's not working, how can i fix this?
image_editable.text((94,475), title_name, (255, 255, 255), font=title_font)
image_editable.text((59,517), title_id, (255, 255, 255), font=title_font)
error
in _multiline_check
return split_character in text
TypeError: argument of type 'int' is not iterable
Sorry never used PIL
btw can i dm you ?
Can u ask here?
Hey can anyone pls help me make a translator??
error are like monsters 😔
Ya
Sorry never used that module
Man just split the word for example orange into o then convert it into your language and repeat this process
anyone else who know ?
!pypi async_google_trans_new use this
why is this
Dude no wtf
import discord
from discord_slash import SlashCommand
from discord.ext import commands
import os
import datetime
client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def load(ctx, extension):
client.load_extension(f'cogs._{extension}')
@client.command()
async def unload(ctx, extension):
client.unload_extension(f'cogs._{extension}')
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
client.run('')
U need to use commands.Bot instead of discord.Client
He wants to make his own secret language
On what line?
😂
