#discord-bots

1 messages · Page 664 of 1

cedar fern
#

if you are ez

upbeat otter
#

dms closed

sullen sedge
#

is it ok to use subprocesses for bot commands?

upbeat otter
#

it gets irritating dealing with 3-4 people at once lol

cedar fern
royal jasper
#

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?

cedar fern
#

check this out

upbeat otter
#

my eyes

sullen sedge
#

make a .replit named file

#

and add this

#
language = "python"
run = "python main.py"
upbeat otter
# cedar fern

replace os.getenv line with:

client.run(os.environ["test"])
cedar fern
upbeat otter
sullen sedge
upbeat otter
sullen sedge
fair axle
#

do slash commands exist in nextcord?

upbeat otter
cedar fern
# upbeat otter not required

okay in the test file i had written token and copied my bot token and after running that my bot is still offline

sullen sedge
cedar fern
sullen sedge
#

is it ok to use subprocesses for bot commands?

upbeat otter
#

they are visible to all

slate swan
#

And don't forget that please

upbeat otter
#

lol

sullen sedge
#

indentation

upbeat otter
#

indents too

slate swan
#

Same for the if statement above

sullen sedge
#

lol

tough lance
#

Lmao

cedar fern
upbeat otter
astral cobalt
#

😆

cedar fern
sullen sedge
#

add ur token there

leaden cargo
#

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
cedar fern
pale palm
#
token = input("Token: ")```
Is this visible on replit?
cedar fern
#

secret tab ryt ??

sullen sedge
lament mesa
cedar fern
astral cobalt
#

I know exactly what video your watching for that @cedar fern

pale palm
#

Or.

sullen sedge
cedar fern
#

w8

slate swan
unkempt canyonBOT
#

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

sullen sedge
upbeat otter
astral cobalt
#

@sullen sedge You can still read them xD

upbeat otter
upbeat otter
#

cuz why not

lament mesa
sullen sedge
#

is it ok to use subprocesses for bot commands?
my question not answered ;-;

maiden fable
#

It's online

cedar fern
upbeat otter
astral cobalt
#

i feel like using dark mode now

upbeat otter
#

you have your key there

#

nice

cedar fern
upbeat otter
#

and fix your indents

sullen sedge
astral cobalt
#

Eevee you wanna gimme a hand real quick?

leaden cargo
#

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
astral cobalt
#

Im having trouble getting my bot to role change people

mystic grotto
cedar fern
maiden fable
#

@astral cobalt what's up

cedar fern
#

and how to fix that

unkempt canyonBOT
#

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

mystic grotto
maiden fable
#

I love spamming big tags

astral cobalt
#

@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)

mystic grotto
upbeat otter
cedar fern
sullen sedge
upbeat otter
cedar fern
astral cobalt
#
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'```
velvet tinsel
#

Oh sweet

upbeat otter
maiden fable
leaden cargo
#

i think so, at least its working rn

astral cobalt
#

I pass in the role as an arg dont i?

upbeat otter
#

!d discord.Embed

unkempt canyonBOT
#

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.
upbeat otter
#

@mystic grotto

#

it takes a name parameter

maiden fable
#

Ngl I am confused whom to help and whom to not 😬

mystic grotto
maiden fable
#

Yea

upbeat otter
mystic grotto
#

ohk

maiden fable
#

Ah u talking about field

#

!d discord.Embed.add_field

unkempt canyonBOT
#

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.
astral cobalt
#

That code doesent work @maiden fable

mystic grotto
#

so i can do it name="Name" and stuff like that right

maiden fable
upbeat otter
astral cobalt
#

*element Andrew Air

maiden fable
astral cobalt
#
async def element(ctx, member : discord.Member, role : discord.Role):
  await member.add_roles(role)```
maiden fable
#

Nvm

mystic grotto
#

thx sooo much eevee and hunting the grinch

maiden fable
#

!d discord.ext.commands.RoleConverter

unkempt canyonBOT
#

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)...
maiden fable
#

Use this (:

#

commands.RoleConverter().convert(role)

#

Or something I don't remember lemme see

boreal ravine
#

!d disnake.ext.commands.RoleConverter better

astral cobalt
#

instead of what?

maiden fable
#

role = await RoleConverter().convert(ctx, role)

#

Just do this

lament mesa
maiden fable
lament mesa
fair axle
#

does nextcord have slash commands?

astral cobalt
#

@fair axle I dont think so

fair axle
#

:(

#

my whole bot is based on slash commands

astral cobalt
#

Nvm

maiden fable
#

BTW @visual island there's a possibility they flagged my bot ¯_(ツ)_/¯

astral cobalt
#

@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

maiden fable
#

Your bot doesn't have the perms to add roles

astral cobalt
#

My god

#

Im blind thank you

maiden fable
#

(:

leaden cargo
#

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

astral cobalt
#

How do you get what role a person has?

maiden fable
unkempt canyonBOT
#

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.
astral cobalt
#

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?

maiden fable
#

utils.get(ctx.author.roles, name="")

#

Or exchange name with any other property

stiff nexus
#

how do i make the bot to dm a interaction user when he uses a buuton?

astral cobalt
#

and how do I get the member name?

unkempt canyonBOT
#

property name```
Equivalent to [`User.name`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.name "discord.User.name")
maiden fable
#

Hahaha

#

U got it (:

astral cobalt
#

darn

#

lol

mystic grotto
#

when i send my first message on the server, the bot counts the xp but after that it doesnt count xp for the user

visual island
maiden fable
#

But yea, that's a possibility

astral cobalt
#

utils is not defined? but im importing the lobaray

mystic grotto
#

when i send my first message on the server, the bot counts the xp but after that it doesnt count xp for the user

leaden cargo
#

How do i set the bot to send a mensage on to a specific channel?

final bolt
#

my bot its off why??

leaden cargo
#

I rly need help, im trying to do it for a few hours

spring flax
#

!d discord.abc.Messageable.send @leaden cargo

unkempt canyonBOT
#

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**.
leaden cargo
#

Hm

maiden fable
#

Look closely

boreal ravine
#

sad

final bolt
leaden cargo
#

Like how can i praticly define where i have to out the channel só ir sends ir there?

spring flax
spring flax
#

Or to another channel

#

okay

leaden cargo
#

Its to another channel

#

Im gonna Try something brb

spring flax
#

Just do
channel = bot.get_channel(channel ID)

leaden cargo
#

And then send the mensagem right?

spring flax
#

And then
await channel.send(....)

#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
leaden cargo
#

Alright Imma test it out!

loud junco
#

can i share a few command that do the same thing?

#

like p and profile

spring flax
#

what?

mystic grotto
#

i figured it out

spring flax
#

were you using json?

loud junco
#

something like

@bot.command(name = 'p' or 'profile')
#

but correctly

leaden cargo
#

Thx for the help guys!

spring flax
loud junco
#

what is aliases

spring flax
#

like if prefix is ?
Doing ?p or doing ?profile will call the same command

astral cobalt
#

await member.add_roles(role) Can I pass a string to this?

astral cobalt
#

adding a role to somone

tough lance
astral cobalt
#

Can I pass in the role name

#

or does it have to be the role id?

spring flax
#

you can get the role object with the name, yes.

loud junco
astral cobalt
#

How do I get a role object?

spring flax
spring flax
astral cobalt
#
async def element(ctx):
  member = ctx.message.author
  role = "Air"
  await member.add_roles(role)``` I have this but it fails when I do
loud junco
#
@bot.command(aliases ={ 'p',  'profile'})
#

like this?

spring flax
#

use [ and ]

loud junco
#

oo ok

#

@bot.command(aliases =['p', 'profile'])

#

this?

spring flax
spring flax
loud junco
#

THANKS

spring flax
#

YOUR WELCOME

astral cobalt
#

And how do I check if a member has a certain role?

spring flax
astral cobalt
#

yeah

spring flax
#

use this decorator

#

wait oops

#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@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")
astral cobalt
#

use that instead of @client.command()

spring flax
#
@commands.has_role("name")
spring flax
#

so use both

astral cobalt
#

Does it matter which one goes first

spring flax
#

put @client.command() first

sage otter
#

it really doesn’t but that’s ok ig.

spring flax
astral cobalt
#

And if the user doesent have that role it will error, how should I catch that? or should I even catch it?

sage otter
#

stay consistent for readability sake ofc

boreal ravine
spring flax
unkempt jewel
#

how can i got problem here, idk

slate swan
#

the problem is the fact that you have toolbar on top

#

ugly asf

astral cobalt
#

Wait I put an error where?

sage otter
#

Do you know how to do error handling yet?

#

Locally or globally?

astral cobalt
#

Well i usually use try execpt

#

but im not sure how to do it in this context

spring flax
#

!d discord.ext.commands.MissingRole This is the error that comes from a check failure of @commands.has_role

unkempt canyonBOT
#

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.
unkempt jewel
spring flax
astral cobalt
#

no

spring flax
#

okay

spring flax
#

in your eh

#

error handler

astral cobalt
#

So I need to make a seperate error handler that will catch errors from any of my calls?

spring flax
#

do you already have an error handler?

astral cobalt
#

No

sage otter
#

This is the one that dpy recommends

spring flax
#

You can either do it for each command, or do an on_command_error event

loud junco
#
@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

spring flax
#

wrong bracket

loud junco
#

ik

#

i fixed it

#

thanks btw :D

astral cobalt
#

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")

spring flax
#

huh

spring flax
#

that doesn't go inside try

#

that goes as a command decorator

loud junco
#

what is this

spring flax
#
@bot.command()
@commands.has_role("role name")
async def...```
tough lance
astral cobalt
#

Okay thats what I have but im just confused on how to catch that error inside the def

loud junco
# loud junco
@bot.command(aliases =['p',  'profile'])
@commands.cooldown(1, 1, commands.BucketType.user)
async def profile(ctx):
  userid = str(ctx.author.id)
tough lance
#

That goes for every command

loud junco
#

so what do i do

#

i cant define a function without name

#

🤣

astral cobalt
#

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"

spring flax
astral cobalt
#

Would I have to check inside the definition instead of having the decerator

loud junco
tough lance
spring flax
#

Tylerr sent a link on it above

tough lance
#

Else there is a name kwarg too

tacit horizon
#

can i run 2 bot in one python file

loud junco
visual island
tawdry perch
#

where can I get invite to disnake server?

tough lance
tough lance
tawdry perch
#

what?

tacit horizon
tawdry perch
#

ty

visual island
tough lance
#

Wait server

tacit horizon
#

;-;

tough lance
#

Depends on the server

visual island
#
asyncio.create_task(bot1.start())
bot2.run()
#

something like that

tacit horizon
#

;--;

visual island
#

hmm?

tacit horizon
#

i dont got it but ok

tough lance
tacit horizon
#

ohh

tough lance
#

Its not recommended tho

tacit horizon
#

huh ok

#

bro how i can reply with the member name in async def on_message(message):

tawdry perch
#

why is there so many github repos with name "disnake"

slate swan
#

Thats really cool and funny lol

tawdry perch
#

I can't find the original one

tacit horizon
#

its like i say hello ''hello"
bot says = hello @tacit horizon

loud junco
#
@bot.group()
@commands.cooldown(1, 1, commands.BucketType.user)
@bot.command(aliases = ['craft 1'])
async def craft(ctx):
  await ctx.send('hello world')
tawdry perch
visual island
loud junco
#

i have a bot.group under it

#

tons of craft.command

#

so i do craft.command()?

tacit horizon
#

help ! ;-;

slate swan
visual island
tawdry perch
#

does disnake support slash commands in cogs?

visual island
unkempt canyonBOT
slate swan
loud junco
#
@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
visual island
#

just remove the last decorator

#

entirely

loud junco
#
@bot.group()
@commands.cooldown(1, 1, commands.BucketType.user)
(aliases = ['craft 1'])
async def craft(ctx):
  await ctx.send('hello world')
```like this?
#

=.=

astral cobalt
#

@commands.has_role("Air") Throws an error if the user doesent have the right role, im confused on how to catch it

visual island
loud junco
#

ok

visual island
unkempt canyonBOT
#

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")
loud junco
#

lemme try

visual island
#

or is it MissingRole cant remember

loud junco
#

when i use craft blah blah

slate swan
visual island
visual island
slate swan
#

you can use groups or args to have spaces in commands

#

is there any way to catch TimeoutError in the on_command_error event?

loud junco
#

so i need to do craft and craft 1 two different thing?

#

but they function the same way tho

astral cobalt
#

@visual island How do I use the exception discord.ext.commands.CheckFailure(message=None, *args). Where would I put it?

loud junco
#

is this error handler

astral cobalt
#

yeah

loud junco
#
@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
astral cobalt
#

So I would have this function after my client.command() and if my client.command() fails it will go to this error function?

loud junco
#

its at the last one

#

right above the token thing

visual island
#

it's MissingRole not CheckFailure mb

loud junco
#

just change the blahblah in commands.blahblah

astral cobalt
#

it says bot is not defined

visual island
#

it's the bot instance, you probably named it client or something

loud junco
stiff nexus
#

how do i make the bot send a message when a user uses a buttons but the message should not be replying

astral cobalt
#

@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.

visual island
#

show code

#

of your error handler

astral cobalt
#

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

loud junco
#

nono

#

thats for my bot

#

i send that for example

astral cobalt
#

Thank you!

loud junco
#

:D

#

is it working now?

#

imagine u can help people but u cant help yourself 🥲

cloud tundra
#

Ayo
Does anyone know how i can run an async function using a lambda?

#

Im trying to make a queue for my bot

visual island
#

hmm?

visual island
loud junco
#
@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

cloud tundra
visual island
#

3 sec is too fast

cloud tundra
#

im using the lamba as an after function

visual island
unkempt canyonBOT
#

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...
visual island
#

you can use while True loop or tasks.loop

visual island
visual island
#

hmm, why do you need create_task?

slate swan
#
@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
visual island
#

you need to read the file

pale palm
#

I'm currently host my discord bot on replit, and it's working.

visual island
#

cool CH_ThumbsUpSmile

pale palm
#

And, now my bot will run 24/7?

#

Without sleeping?

untold token
#

!d asyncio.Queue

unkempt canyonBOT
#

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).
untold token
slate swan
untold token
#

Replit's hosting isn't consistent at all and replit isn't even made for hosting

astral cobalt
#

@commands.has_role(role) Is there a way to include multiple roles? If user has this role OR this role OR this role

pale palm
untold token
#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@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")
astral cobalt
#

commands.has_any_roles("role 1", "role 2", "role 3")

untold token
#

Nonon9

#

Don't do this

#

You should never change status in an on_ready event

leaden cargo
#

why is it sending the message in the same channel iff i put another channel's id?

    await message.channel.send( content )```
slate swan
untold token
#

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

visual island
untold token
#

Sorry if I didn't understand the question

visual island
visual island
untold token
#

and you can use asyncio.Queue to queue stuff

pale palm
visual island
leaden cargo
#

why is it sending the message in the same channel iff i put another channel's id?

    await message.channel.send( content )```
visual island
#

asyncio.Queue is not the thing for running coroutines, its just for handling the Tasks queue

untold token
#
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

slate swan
#

how do I connect a google drive api with my discord bot make changes in a file when a certain command is used?

untold token
#

it creates a task that runs asynchronous

astral cobalt
#

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?

untold token
#

if they want to run synchronous functions in asynchronous code they would need to use executor

visual island
#

loop.run_in_executor

slate swan
pale palm
visual island
#

but yea, they want to run a coroutine in sync func not sync/blocking function in an async

slate swan
untold token
#

!d asyncio.loop.run_in_executor

unkempt canyonBOT
#

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:
untold token
#

Yeah

pale palm
astral cobalt
#
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.

untold token
#

Cloud storage API??

visual island
untold token
#

MongoDB isn't any API

#

It's a database

slate swan
royal lichen
#

That's bad practice, you should put help_command=None while creating the bot object

untold token
#

Yeah

#

help_command=None is way better

slate swan
#

Indentation please.

untold token
#

Hm yeah

tall dust
#

@slate swan remove the invite link from your code before you paste it

#

yeah that

untold token
#

Look at indentation

visual island
#

unindent the async def and the last line

untold token
#

Yes

visual island
#

and don't await the .start()

astral cobalt
#

@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?

visual island
#

pinging the wrong guy lol

cursive coral
#

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.

astral cobalt
#

Oops lol

untold token
#

it's an awaitable

visual island
#

!d discord.ext.tasks.Loop.start

unkempt canyonBOT
leaden cargo
#

TypeError: send() takes from 1 to 2 positional arguments but 3 were given

untold token
#

iirc

leaden cargo
#

whats that error?

visual island
#

yeah asyncio.Task is awaitable

leaden cargo
#

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

untold token
#

The docs confused me

visual island
leaden cargo
#

and i have done

author = str(message.author)```
royal jasper
#

how can I change user's nickname on specific server?

leaden cargo
#

i tried without the str first and then with it

visual island
unkempt canyonBOT
#

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...
cursive coral
#

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.

royal jasper
astral cobalt
#

@visual island Yeah non of my commands are being displayed

unkempt canyonBOT
#
Did you mean ...

» sql-fstring
» f-strings

astral cobalt
#

I dont think im getthing them right

visual island
#

!f-strings

unkempt canyonBOT
#

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.

tawdry perch
#

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")

visual island
astral cobalt
#

@visual island No Ihavent

#

at the top?

#

Got it

visual island
astral cobalt
#

Thank you

visual island
#

you dont need self.client.commands

astral cobalt
#

I dont?

visual island
#

client.commands is enough

astral cobalt
#

Gotchu I see

visual island
#

as youre not in cog

boreal ravine
#

hm

visual island
#

dont await last line

visual island
pale palm
#

Could you send the full code?

boreal ravine
#

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

visual island
#

yeah you don't

untold token
#

Yeah you don't need await start()

#

The docs confused me

boreal ravine
#

lmao

visual island
#

you probably missed a bracket/smth

full valley
#

Is there a way to add a line in between team1 & team2 and the Makes lobby fields?

#

like a blank line

boreal ravine
#

nice

full valley
velvet tinsel
#

hello Kayle

boreal ravine
#

hello dekriel

full valley
#

U know everything I swear YEP

velvet tinsel
#

finally
someone called me Dekriel

boreal ravine
#

yes

velvet tinsel
#

I dont wanna go ot because I'll get muted again so

#

you indented it wrong

boreal ravine
#

import tasks

velvet tinsel
#

as well

boreal ravine
#

import ext.commands

boreal ravine
velvet tinsel
#

||imagine not indenting it||

forest spear
#

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?

velvet tinsel
#

what's user

forest spear
#

Yeah I've tried that

forest spear
#

Doesn't work

velvet tinsel
#

show code

forest spear
velvet tinsel
#

you probably forgot to define user or maybe you got it wrong

boreal ravine
#

!d discord.User.avatar

unkempt canyonBOT
#

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").
velvet tinsel
boreal ravine
forest spear
#

That would only be users in the guild I want users outside the guild too

velvet tinsel
#

I mean you can try this but he has the ID I think

boreal ravine
velvet tinsel
#

but

boreal ravine
#

!d discord.User lol

unkempt canyonBOT
#

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.
velvet tinsel
#

you cant mention users in other guilds 😭

boreal ravine
#

he has id ig

velvet tinsel
#

ok 😭

boreal ravine
#

!d discord.ext.commands.Bot.get_user <=

unkempt canyonBOT
velvet tinsel
#

ok 😭

boreal ravine
#

@forest spear show me your code

forest spear
velvet tinsel
#

I said that already 😭

#

code pls 😦

forest spear
#

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")

boreal ravine
#

hmm

velvet tinsel
#

where's the error again

forest spear
#

embed.set_author

#

In icon_url to be specific

velvet tinsel
#

is that where the error was? aight

velvet tinsel
#

I mean it depends what mod is

boreal ravine
#

user.avatar only, not quotes

forest spear
#

Tries .format too and in variable but it didn't work

boreal ravine
velvet tinsel
#

😭 I like crying

velvet tinsel
untold token
#

user.avatar.url
If it is dpy 2.0

velvet tinsel
#

but

boreal ravine
forest spear
velvet tinsel
#

that's what it says in the stack overflow answer

boreal ravine
velvet tinsel
#

userAvatar = member.avatar_url 😭

untold token
#

and icon_url takes an url which is a string

velvet tinsel
#

kayle vs ! a

boreal ravine
cursive coral
#

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.

forest spear
#
embed.set_author(name=f"{user}", icon_url={user.avatar_url})
AttributeError: 'str' object has no attribute 'avatar_url'
untold token
#

!d discord.Member.avatar

boreal ravine
forest spear
#

The exact same thing works fine in my avatar command but doesn't work in my modlogs

velvet tinsel
#

what is the { for

forest spear
untold token
#

Huh

boreal ravine
#

yes

forest spear
#

Doesn't work either lol

boreal ravine
#

!d discord.User.avatar @untold token

unkempt canyonBOT
#

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").
boreal ravine
#

url attr is separate

velvet tinsel
boreal ravine
#

!d discord.Asset.url <=

unkempt canyonBOT
boreal ravine
untold token
#

icon_url takes an url though

forest spear
#

I even tried uninstalling discord.py and reinstalling it but idk it doesn't work

forest spear
velvet tinsel
#

AttributeError: 'str' object has no attribute 'avatar_url'  is it to do with the str?

#

I'm a bit slow

untold token
#

user is an str?

forest spear
visual island
#

which is a string

stiff nexus
#

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
velvet tinsel
#

I hate it when that happens

forest spear
#

Thank you genius person

velvet tinsel
#

icy saves the day ^_^

boreal ravine
#

this is why you dont make params/vars with the same name

visual island
#

lol I read your code 20 times

forest spear
#

Dumb me

visual island
#

then I realized that

velvet tinsel
#

icy fast reader

boreal ravine
forest spear
#

I've been at this for well over an hour thank you icy

velvet tinsel
untold token
#

Hm

velvet tinsel
#

I'm still making my IDE, maybe I can use dpy on there someday
working on terminal 🙂

boreal ravine
#

wow nice

stiff nexus
untold token
#

Sup hunter

velvet tinsel
maiden fable
kindred drum
#

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)```
velvet tinsel
#

huntering the grinch
i'll call you grinch hunter from now

stiff nexus
#

i have a subclass of context tho

boreal ravine
ebon island
#

What is the best current method for a Discord bot to play an audio file from local system or otherwise?

boreal ravine
velvet tinsel
untold token
velvet tinsel
#

whenever you guys start typing I get scared

boreal ravine
#

why

velvet tinsel
ebon island
#

is FFMPEG the only current method?

velvet tinsel
stiff nexus
# boreal ravine use that then
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'
kindred drum
velvet tinsel
#

no......maybe...

visual island
untold token
#

!d discord.Message.remove_reaction

unkempt canyonBOT
#

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.
boreal ravine
kindred drum
stiff nexus
untold token
#

Subclassed context are fine

#

and useful in many cases

stiff nexus
#

ik but sometimes.....

astral cobalt
#

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?

boreal ravine
astral cobalt
#

I do have error code but my error code has if isinstance(error, commands.MissingRole):

stiff nexus
astral cobalt
#

And I want two different prints depending on which def the error is in

velvet tinsel
#

I meant Destro but ok

untold token
velvet tinsel
untold token
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

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.
velvet tinsel
#

you can try this and use an error handler for it

astral cobalt
#

Thanks

maiden fable
boreal ravine
velvet tinsel
maiden fable
royal jasper
#

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?
velvet tinsel
untold token
velvet tinsel
untold token
#

!d discord.Member.display_avatar

unkempt canyonBOT
#

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.
untold token
#

Huh

#

It's an asset

#

But icon_url takes an url

velvet tinsel
boreal ravine
royal jasper
velvet tinsel
#

you can create different json files for different things

velvet tinsel
untold token
#

That's weird

kindred kindle
#
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

untold token
#

Well I was kinda right then

#

display_avatar returns an url

boreal ravine
royal jasper
velvet tinsel
untold token
#

Don't use json files as a database

#

No

royal jasper
untold token
#

Its not a database

boreal ravine
#

use mongo, its way easier and its like json

untold token
#

Yeah

royal jasper
untold token
# royal jasper why?

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

boreal ravine
untold token
#

and if you use it, you will deal with more problems than ever

boreal ravine
#

you could watch a tutorial for the functions (pymongo, a wrapper for it) though

untold token
#

Yeah pymongo isn't asynchronous

#

So you would need to use motor

boreal ravine
#

bruh

royal jasper
untold token
#

Using synchronous modules / libraries in asynchronous code is a very very bad idea

boreal ravine
#

what syntax

boreal ravine
untold token
#

Yeah it is

boreal ravine
#

hm

untold token
#

It took you that long to type hm??

boreal ravine
#

i was typing something else

kindred drum
#

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

boreal ravine
#

i didnt wanna get muted again though so i sent hm 🙂

kindred drum
#

I hate reactions man

ebon island
#

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?

crimson tendon
kindred drum
honest vessel
#

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

crimson tendon
modest plover
#

Hey, how do I make it so the index.py file reads the token I put into the config.json file?

honest vessel
#

by reading the json file

modest plover
#

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

honest vessel
#

google python3 how read file

kindred drum
clear rapids
#

is there any way to check time spent on voice channel of a particular user?

honest vessel
#

@modest plover as i said google python3 how read file

crimson tendon
kindred drum
#

AttributeError: 'Reaction' object has no attribute 'user'

#

thats the actual error

opal skiff
#

is the sourcecode of the python bot official? i want to do an eval command

#

nvm i found it

wanton veldt
#

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'

wanton veldt
#

ok

#

let me check if its ok

#

YESSS

solar pike
#
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

slate swan
#

@commands.command should not be there , client variable is undefined at the place you defined slash var

bleak karma
#

is there a way to make the bot count all the channels inside a category?

maiden fable
unkempt canyonBOT
#

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.
bleak karma
#

oh alright

outer basalt
#
@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?

slate swan
outer basalt
#

idk whats happening its printing both embed but not sending them

slate swan
#

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?

maiden fable
outer basalt
#

sec

slate swan
#
@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

slate swan
slate swan
#

intents issue mb

maiden fable
#

Yea

slate swan
outer basalt
maiden fable
#

Tf?

#

the embeds keep on increasing

#

Can I see a screenshot of what it sends?

slate swan
unkempt canyonBOT
#

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.

outer basalt
#

it didnt print the msg delete

maiden fable
#

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

unkempt canyonBOT
slate swan
#

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

median cosmos
#

Hey, can someone help me with an error here?

outer basalt
#

it works properly if i do it alone like only triigger msg delete event

maiden fable
slate swan
maiden fable
#

Can u try removing the try except to see if there ain't any errors?

median cosmos
outer basalt
#

alr

slate swan
maiden fable
slate swan
median cosmos
slate swan
outer basalt
#

i tried sending it via bot without any error handler, same issue

maiden fable
royal jasper
#

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?
maiden fable
median cosmos
maiden fable
slate swan
median cosmos
#

@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)

maiden fable
#

Which line?

median cosmos
#

so essentially it all fails at the sendmaptochat function

maiden fable
#

Wait

#

Why do u have all the commands inside a function?

median cosmos
#

Is that bad?

maiden fable
#

Very bad

median cosmos
#

uhm

#

I should try to remove the main() function right?

maiden fable
#

Yea

median cosmos
#

Then im getting this error 'RuntimeWarning: coroutine 'RustSocket.connect' was never awaited
socket.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback'

slate swan
#

Does "except Exception as e:" work on python 3.5.3?

outer basalt
#

and not trigger other events

slate swan
#

I don't know what that is
but in on_ready? thinkmon

median cosmos
# maiden fable U can do all that 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

unkempt canyonBOT
#

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:

https://paste.pythondiscord.com

median cosmos
#

error in line 50 and line 27

#

line 50 is await sendmaptochat() and 27 the try to send "hello" in the channel

wanton veldt
#

does anyone have a good restart command?

#

id only

final iron
#

You could use cogs and just reload them without any downtime to the bot

median cosmos
#

@maiden fable Are you still here?

wanton veldt
maiden fable
median cosmos
#

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

slate swan
outer basalt
#

sec ill show the code

slate swan
#
@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)
outer basalt
slate swan
#

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
kindred drum
#

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

slate swan
slate swan
wanton veldt
#

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.")

maiden fable
#

U didn't call it lol

slate swan
#

.command()

wanton veldt
#

oh fuc

tiny ibex
maiden fable
#

???

verbal cairn
#

Commands is_owner is for person who made the bot

wanton veldt
#

is a privat bot

slate swan
#

Hi

tiny ibex
maiden fable
#

Hi

slate swan
#

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
slate swan
#

How to make a translator

kindred drum
tiny ibex
slate swan
#

I wanna make one

tiny ibex
#

Or you just wanna implement that feature in your bot?

slate swan
#

Na its for secret language

tiny ibex
slate swan
#

Like 1=a b=2 c=3

tiny ibex
#

bruh

slate swan
#

And when we say a word

#

Like orange

#

It prints 943 758276

tiny ibex
#

Sir

wanton veldt
slate swan
#

Yes

tiny ibex
#

I failed to understand

slate swan
#

Aa

tiny ibex
slate swan
#

K

limber cosmos
#

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.")```
slate swan
#

Do u play anigame

tiny ibex
slate swan
#

K

tiny ibex
#

I am not interested inn gaming at all

slate swan
#

Do u know how to make one?

tiny ibex
slate swan
#

Make games

quick gust
tiny ibex
slate swan
#

K

#

What’s lua/

#

?

quick gust
#

A language...

slate swan
#

K

median cosmos
#

@maiden fable Do you have any idea how I could fix the problem?

maiden fable
tiny ibex
slate swan
#

K i have a question

#

Is it possible to make a 2d game in phyton?

quick gust
#

pygame would be better I believe

maiden fable
#

Yea

slate swan
#

K

maiden fable
#

Or arcade, but this aint the correct channel

slate swan
#

?

maiden fable
slate swan
#

K

lucid prism
#

how can i fix this error ?

slate swan
#

I don’t wanna make a game

#

Tho

maiden fable
slate swan
lucid prism
#
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'```
lucid prism
slate swan
#

K

lucid prism
lucid prism
maiden fable
lucid prism
#

ohh file should be in config folder 👀

#

im a dumb man

slate swan
#

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
maiden fable
#

Sorry never used PIL

lucid prism
maiden fable
#

Can u ask here?

lucid prism
#

ok

slate swan
#

Hey can anyone pls help me make a translator??

lucid prism
#

error are like monsters 😔

slate swan
#

Ya

maiden fable
#

Sorry never used that module

tiny ibex
lucid prism
#

anyone else who know ?

maiden fable
unkempt canyonBOT
junior verge
#

why is this

junior verge
#
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('')
maiden fable
tiny ibex
junior verge
tiny ibex
#

😂