#discord-bots

1 messages · Page 662 of 1

tame marsh
#

im normally doing it thorugh arguments

#

but here I need to get it through id

#

pls help

sage otter
#

!d discord.ext.commands.Bot.get_user

unkempt canyonBOT
tame marsh
#

yes

sage otter
#

You referring to that?

mystic grotto
tame marsh
#

im gettting it from a RawReactionActionEvent

#

ill try it with that

#

thx

#

disnake.utils.get(bot.get_all_members(), id=payload.user_id)

#

like this it doesnt work

boreal ravine
#

i mean try it and see

sage otter
#

I don’t understand why people use it utils.get if they have an id

#

Iterating unnecessarily

tame marsh
#

idk why i did it

boreal ravine
#

agreed, you should only use get() func to search for names in an iterable

visual island
tame marsh
#

from cache

mystic grotto
#

so instead of $set i put what

boreal ravine
mystic grotto
#

thought so

boreal ravine
#
{'$set': {'key': value}}
tame marsh
tardy swallow
#

ctx.message.author doesnt work in slash commands for some reason, how can I get the author then?

tame marsh
tame marsh
#

dislash or disnake probably

boreal ravine
tame marsh
boreal ravine
tame marsh
boreal ravine
tame marsh
mystic grotto
#

great news, i only get 2 errors now

boreal ravine
tame marsh
#

👍

tame marsh
boreal ravine
#

!unbound

boreal ravine
tame marsh
mystic grotto
#

i did?

boreal ravine
#

use the global keyword on level

boreal ravine
visual island
#

!botvar when

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

boreal ravine
mystic grotto
boreal ravine
visual island
velvet tinsel
#

Hi icy

tame marsh
#

why do so many ppls use dpy

velvet tinsel
#

Because it’s good

boreal ravine
tame marsh
velvet tinsel
#

I just like bots

tame marsh
#

e.g disnake is dpy in better

tame marsh
visual island
#

hi

velvet tinsel
#

in better 😭

tame marsh
#

its a fork of dpy

mystic grotto
#

y am i getting syntax error

tame marsh
#

bruh

#
@client.command()
@has_permissions(administrator=True)
async def restart(ctx):
    if ctx.author.id == 315485035320836096:
        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()
    else:
        errorperm_embed = discord.Embed(title='Access Denied!', description='This command is `OWNER` only. You are not allowed to use this. Try not to execute it another time.', color=0xFF0000)
        errorperm_embed.set_footer(text=ctx.author)
        await ctx.channel.send(embed=errorperm_embed, delete_after=10.0)```

like this it should work
wanton veldt
#

ty

mystic grotto
tame marsh
mystic grotto
#

also im new to this so it might be like the stupidest mistake lol

tame marsh
#

and shouldnt it be @commands.has_permissions()?

tame marsh
mystic grotto
tame marsh
#

+=1 is trying to add = to sth

#

and u dont use global like this

mystic grotto
boreal ravine
mystic grotto
visual island
visual island
#

oops I havent replied

tame marsh
boreal ravine
boreal ravine
tame marsh
#

i guess

boreal ravine
mystic grotto
tame marsh
#

if it is bigger as 5?

mystic grotto
#

no

tame marsh
#

what else?

mystic grotto
#

im tryna add 1 to the current value of level

#

wait i could just do level= level + 1 right

boreal ravine
#

yes

mystic grotto
#

BRUH

boreal ravine
#
level += 1
``` easier
tame marsh
mystic grotto
tame marsh
boreal ravine
boreal ravine
tame marsh
#

then sry @mystic grotto

#

my mistake

mystic grotto
visual island
#

!e
a = 1
a += 1
print(a)

unkempt canyonBOT
#

@visual island :white_check_mark: Your eval job has completed with return code 0.

2
visual island
#

would like to have ++ in python tho

boreal ravine
#

oo like in js

visual island
#

yeah

mystic grotto
tame marsh
#

or goto function

#

would be pretty usefull too

boreal ravine
#

lots of operators that even I don't know what it does

tame marsh
boreal ravine
#

i dont know the @ and | but I think | is for typing

visual island
tame marsh
#

what the hell is >> or <<

mystic grotto
visual island
#

bit shift

tame marsh
#

never used until yet xD

#

btw is there a pip freeze but only for the active project?

boreal ravine
#

u can do pip show module tho

tame marsh
#

lol

#

not found

#

oh wait

#

im stupid

boreal ravine
#

lmao

tame marsh
#

found it

mystic grotto
#

i dont get an error when i send a message

#

but i get an error when i do a command

maiden fable
mystic grotto
#

uhm

#

anyone

maiden fable
#

Hm?

summer radish
#

so i was following a tutorial but i get this error

visual island
#

use the name kwarg

summer radish
#

can someone help me

#

the guy who was doing the tutorial doesnt seem to get the error even though im pretty sure i didnt write anything different comparing his

tame marsh
#

get_member doesnt exist

sage otter
#

!d discord.Guild.get_member

unkempt canyonBOT
tame marsh
#

thx

visual island
mystic grotto
visual island
#

db[...].value

summer radish
#

alright lemme try

visual island
mystic grotto
#

ok

summer radish
#

but the thing is

#

the guy created a $new command that adds new responses to the database

#

so when i do the $new command, it gets added..thats working

#

the guy also created a del command that removes responses added by users in the database

#

when he runs the del command...the bot responds like this

wanton veldt
#

help? ```py
@client.command()
@commands.has_permissions(administrator = True)
async def restart(ctx, seconds:float):
await ctx.message.delete()
embed = Embed(title = "OFF", description = f"{ctx.message.author.mention} turned off me for {round(seconds)} seconds", color = Color.red())
await ctx.send(embed = embed)
await client.close()
sleep(seconds)
await client.connect()
embed = Embed(title = "Turned on", description = f"I came back after {round(seconds)}", color = Color.green())
await ctx.send(embed = embed)

#

i have all the perms

summer radish
#

he does $del 0

#

and bot responds

#

['command 1 added by user', 'command 2 added by user']

#

when i do the same thing, the bot just responds []

#

anyone help?

mystic grotto
#

idk whatto do

maiden fable
#

!positional-keywords

unkempt canyonBOT
#

Positional vs. Keyword arguments

Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.

Example

>>> print('Hello', 'world!', sep=', ')
Hello, world!

The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.

Note
A keyword argument can be passed positionally in some cases.

def sum(a, b=1):
    return a + b

sum(1, b=5)
sum(1, 5) # same as above

Somtimes this is forced, in the case of the pow() function.

The reverse is also true:

>>> def foo(a, b):
...     print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

More info
Keyword only arguments
Positional only arguments
!tags param-arg (Parameters vs. Arguments)

summer radish
#

his code

#

my code

mystic grotto
summer radish
mystic grotto
#

ok

summer radish
#

i get this error but he doesnt

pale palm
#

Why do I get this error?

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'content'```
```py
# This is my code

@commands.command()
async def Annoucement(self, ctx: Context):
    print(ctx.content)```
pale palm
#

But on my second command it's work.

slate swan
#

Does it print?

pale palm
#

Yes.

slate swan
#

You can just do print(ctx) that would work iirc

visual island
wanton veldt
pale palm
#

@visual island @slate swan Thanks, and sorry for ping.

slate swan
visual island
slate swan
#

^

wanton veldt
#

oh ok

slate swan
#

In this case it should be a float

tawdry perch
#

I have always used manual loading of cogs, but now I'm having way too many of them to load (everytime when I make one I have to add it to list and it is becoming unreadable) so how could I implement the loop thing

#

it would be helpful so I can restructure my files again

visual island
#

!d os.listdir

unkempt canyonBOT
#

os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.

*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.

This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.

Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
maiden fable
#

Wait, I thought u already used os.listdir Nipa

tawdry perch
#

so smth like this I would assume ```py
for filename in os.listdir('cogs_folder_or_smth'):
if filename.endswith('.py'):
#load the extension somehow

maiden fable
#

Yea

tawdry perch
#

what if I have like really many of folders?

#

Do I just need a multiple one of those loops

maiden fable
#

No

tawdry perch
#

it will search inner folders as well?

maiden fable
#

yea

#

bot.load_extension(dir.filename[:-3]) after that

tawdry perch
#

dir = ?

#
├───cogs
│   ├───moderation
│   │   └───__pycache__
│   ├───other
│   │   ├───antimusicbot
│   │   └───__pycache__
│   └───__pycache__
``` if I have structure like this? (antimusicbot cog kicks music bots from guild because why not)
maiden fable
#

okay

#

Then cogs.other will be the directory

tawdry perch
#

so I have to make a loop for moderation folder and for the other folder?

visual island
#

yeah, nested loops

#

!d os.walk this one seems promising

unkempt canyonBOT
#

os.walk(top, topdown=True, onerror=None, followlinks=False)```
Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory *top* (including *top* itself), it yields a 3-tuple `(dirpath, dirnames, filenames)`.
tawdry perch
#
ext = []
for filename in os.listdir('cogs_folder_or_smth'):
    if filename.endswith('.py'):
        ext.append("the files")

for filename in os.listdir('2_cogs_folder_or_smth'):
    if filename.endswith('.py'):
        ext.append("the files")

bot.load_extension(ext)
``` I was thinking of smth like that if this makes sense
#

would this make sense, for me it does.

visual island
#

what's the use of the second loop?

tawdry perch
#

I suck at nested loops, well actually in everything that is nested

#
for filename in os.listdir('cogs_folder_or_smth'):
    if filename.endswith('.py'):
        ext.append("the files")
    for filename in os.listdir('2_cogs_folder_or_smth'):
        if filename.endswith('.py'):
            ext.append("the files")
``` might be like this if nested?
visual island
#
for folder in os.listdir("cogs"):
    for sub_filename in os.listdir(f"cogs/{folder}"):
         ... 
tawdry perch
#

good to know

#

Let me try to make it smh

visual island
#

but in the ext you need to append as "cogs.subfolder.filename" not just the filename

tawdry perch
#

yep

#

I will do MyBot.cogs.folder.filename
^ is a module so I ennsure it goes loaded

unkempt jewel
#
client.command()
async def contribute(ctx):
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)

    embed = discord.Embed(title = "Contribution", description = "Contribution to the project is alway welcome, fell free to contribute, edit, clean up, document and improve the source code at: link", color = discord.Color.random())

    neko = neko.img("neko")

    embed.set_image(url = neko)

    await ctx.send(embed = embed)
tawdry perch
#

I just realized I have a lot of files to load ;-;

#

aand it fked up...

tough lance
#

Rip

visual island
#

rename it

tawdry perch
tough lance
unkempt jewel
#

i dont have any command named random

sage otter
#

You're using nekos.py(sync) and requests. Yikes.

slate swan
tough lance
#

Lol

upbeat otter
tawdry perch
obsidian ledge
#

how to i make a command that checks how many people have a certain role then puts it in a embed?

slate swan
#

!d discord.Role.members

unkempt canyonBOT
maiden fable
slate swan
#

!d clear

maiden fable
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Examples

Deleting bot’s messages...
tawdry perch
lethal moat
#
async def MakeATicket(ctx):
    try:
        channel = await ctx.guild.create_text_channel(f"{ctx.author.display_name}")
        await asyncio.sleep(1)
        default_role = ctx.guild.default_role()
        await channel.set_permissions(default_role, send_messages=False, read_messages=False, view_channel=False)
        await channel.set_permissions(ctx.author, send_messages=True, read_messages=True, view_channel=True)
        embed = nextcord.Embed()
        embed.add_field(name="New ticket made", value=f"<#{ctx.author.id}> has started a new ticket!\nClick the button below to close the ticket.")
        await channel.send(embed=embed)
        await ctx.reply("Ticket created!")
    except Exception as e:
        print(e)

'Role' object is not callable
how do i fix this

tawdry perch
#

You are not supposed to call a role object

lethal moat
#

then how do i get the @ everyone role in that server? i need to set permissions for that channel

vocal magnet
#

The everyone role uses the guild ID as the role ID

#

also ctx.guild.default_role()

#

ctx.guild.default_role is an attribute, not a function

#

So don't put the () on the end

lethal moat
#

ahk

#

is there a way i can grab a specific role by its name/id?

sage otter
#

For name you can use utils.get()

#

By ID it’s recommended you use Guild.get_role()

shut mango
#
@bot.command(name='embed')
async def displayembed():
    embed = discord.Embed(
        title='Title',
        description='This is a description',
        colour=discord.Colour.blue
    )

    embed.set_footer(text='This is a footer')
    embed.set_image(url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown-619.png')
    embed.set_thumbnail(
        url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown-619.png')
    embed.set_author(name='Author Name',
                     icon_url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown'
                              '-619.png')
    embed.add_field(name='Field Name', value='Field Value', inline=False)
    embed.add_field(name='Field Name', value='Field Value', inline=True)
    embed.add_field(name='Field Name', value='Field Value', inline=True)
#

why is my code not working?

lethal moat
#

add await ctx.send(embed=embed) in the end lol

shut mango
full valley
#

Guys im getting:
Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

lethal moat
#

your bot probably doesnt have the appropriate permissions then @full valley

full valley
#

Thats weird

full valley
#

Nothing

#

just trying to use my bot

#

each command returns that

slate swan
#

Your doing something thats returning the error

full valley
slate swan
#

^ lol

#

Maybe your doing something that needs perms so add the perms

shut mango
#
@bot.command(name='embed')
async def embed(ctx):
    embed = discord.Embed(
        title='Title',
        description='This is a description',
        colour=discord.Colour.blue
    )

    embed.set_footer(text='This is a footer')
    embed.set_image(url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown-619.png')
    embed.set_thumbnail(
        url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown-619.png')
    embed.set_author(name='Author Name',
                     icon_url='https://cdn.discordapp.com/attachments/909412258826813453/918156142457282580/unknown'
                              '-619.png')
    embed.add_field(name='Field Name', value='Field Value', inline=False)
    embed.add_field(name='Field Name', value='Field Value', inline=True)
    embed.add_field(name='Field Name', value='Field Value', inline=True)

    await ctx.send(embed=embed)
slate swan
#

is it possible for discord bots to stream videos in vc channels?

sage otter
# shut mango why is my code not working?

Btw. Saying something doesn’t work doesn’t help anyone, not even yourself. Instead of just saying "it doesn’t work" or "why does this not work" it’s preferable you post code, errors(if any), what you expect your code to do, and overall intentions.

shut mango
#

any idea why is it not working?

slate swan
shut mango
#

so i can do !embed

#

and it sends the embed

sage otter
shut mango
#

oh

#

i didnt see

#

it has an error

#

and what im trying to do is

#

when i say !embed it sends embed

sage otter
#

that’s a warning. not an error. That’s just bad naming conventions.

#

Your functions name is embed

slate swan
sage otter
upbeat otter
placid meadow
#

Its says colour

slate swan
placid meadow
#

Its suppose to be Color*

slate swan
#

Ah i see my bad

placid meadow
#

Try it its always better i think

sage otter
sage otter
slate swan
placid meadow
#

His embed set name is missing a )

#

He didnt close it

#

Thats why

sage otter
placid meadow
placid meadow
sage otter
shut mango
shut mango
#

you mean there?

sage otter
#

Add parenthesis after blue

placid meadow
sage otter
#

Yes

#

Read the docs

slate swan
#

Yeah i think its needed

placid meadow
shut mango
placid meadow
#

There

shut mango
#

it worked

shut mango
#

() was needed

slate swan
#

LOL

placid meadow
#

Cool

upbeat otter
shut mango
#

oh

shut mango
#

im sorry

#

i didnt see

upbeat otter
tough lance
#

Hmm

stiff nexus
#

help??```py
if msg.channel.id == 869639643167223230 and 888117654931734344:
await msg.delete()

compact harbor
velvet tinsel
#

Ok

#

Hello random person

tawdry perch
#

that's maybe where the message was sent?

sage otter
#

use or you can check if the id is in a list.

velvet tinsel
#

Lojeck jam_cavedude

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
shut mango
#
@bot.command(name="8ball")
async def eightball(ctx, *, question=None):
    embed = discord.Embed(title=f"8ball", timestamp=datetime.datetime.utcnow())
    if question is None:
        return await ctx.reply("Include a message")
    responses = ['Yes', 'No', 'YES YES YES', 'Probably', 'nah']
    res = random.choice(responses)

    await ctx.reply(res)
    embed.add_field(name="Question", value='', inline=False)
    embed.add_field(name='Answer', value=res, inline=False)

    embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
    await ctx.send(embed=embed)

im trying to make 8ball command in embed but it doesnt work

#

the only errors

dense depot
#

its this code causing the issue embed.add_field(name="Question", value='', inline=False)

#

it needs to have a value

lament mesa
#

You could give an empty Unicode for the value of the field

slate swan
#

the value cant be ""

lament mesa
dense depot
#

Is there anyway of accessing a function within a cog file in my main file?

maiden fable
placid meadow
#

I need help , i want a command that i can do example !blacklist ‘id’ and the person wont be able to use the bot anymore , how can that be possible?

boreal ravine
#

save the id somewhere

sick veldt
#

Hello!

#

I need help

boreal ravine
#

then check if the authors id is in that "somewhere" using a global check

boreal ravine
sick veldt
#

Dm?

placid meadow
sick veldt
boreal ravine
#

why dms lol

sick veldt
#

I have alot of doubts so

boreal ravine
#

ask away ig

sick veldt
#

okie

#

Traceback (most recent call last):
File "main.py", line 3, in <module>
from pretty_help import DefaultMenu, PrettyHelp
ModuleNotFoundError: No module named 'pretty_help'

sick veldt
boreal ravine
#

can't use something without obtaining it first

sick veldt
#

okay

#

done

#

it worked

sick veldt
# boreal ravine download the lib

Traceback (most recent call last): File "main.py", line 20, in <module> run() File "main.py", line 17, in run bot.run(token) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run return future.result() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner await self.start(*args, **kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start await self.login(*args, bot=bot) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip'

#

new issue

#

kayle

#

`import discord
from discord.ext import commands
from pretty_help import DefaultMenu, PrettyHelp

from asyncio import sleep
import os
import random

bot = commands.Bot(command_prefix="fe!")
token = os.environ.get("token")

@bot.event
async def on_ready():
print("I'm in")

def run():
bot.run(token)

if name == "main":
run()`

sick veldt
#

Traceback (most recent call last):
File "main.py", line 20, in <module>
run()
File "main.py", line 17, in run
bot.run(token)
NameError: name 'token' is not defined

#

new problem

sick veldt
boreal ravine
sick veldt
#

ok

#

import os
import discord
from discord.ext import commands
from pretty_help import DefaultMenu, PrettyHelp

from asyncio import sleep
import os
import random

bot = commands.Bot(command_prefix="fe!")

@bot.event
async def on_ready():
print("I'm in")

def run():
bot.run(token)

if name == "main":
run()

my_secret = os.environ['token']

boreal ravine
#

bruh

#

add token var back

#

i never told you to remove it

placid meadow
sick veldt
boreal ravine
#

it printed? or what

sick veldt
#

Code worked

#

The bot is online now

#

in the console it said I'm in

sick veldt
slate swan
#

How would I get the webhook url using the name>?

sick veldt
#

name?

slate swan
#

Yes the name of the webhook

maiden fable
unkempt canyonBOT
#

await webhooks()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gets the list of webhooks from this channel.

Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
slate swan
#

Or the webhook in the channel where the command is used

maiden fable
#

Use utils.find or utils.get

slate swan
#

and how would I use that

maiden fable
#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Examples

Basic usage...
maiden fable
#

discord.utils.get(webhooks, name=name)

slate swan
#

can anyone help

#

im trying to make a mute command and it keeps on saying "unindent does not match any outer indentation level"

#

ive tried to make it all correct but it still highlights the end of a bracket and says that

maiden fable
#

there is extra space in the if line

#

See?

#

@slate swan

slate swan
#

it was just that simple mistake

maiden fable
#

Yea

winged arch
#

Hi all, i've been working on a simple template for a discord bot and would like feedback if thats appropriate. The bot works (Again, super simple - just connects and displays presence). The purpose is to be a template to use to build other bots, and im looking for overall feedback regarding the instructions, readability, and ofcourse correctness 🙂 if anyone wants to check it out to provide me any criticism, it can be found here - https://github.com/Chasewb91/slatebot

GitHub

A template for discord bots, providing a "clean slate" to build upon. - GitHub - Chasewb91/slatebot: A template for discord bots, providing a "clean slate" to build upon.

simple gulch
#

I'm trying to implement this into my discord bot to give a shortened url to my users, but not sure how to do that.

--header 'Authorization: Bearer YOURAPIKEY' \
--header 'Content-Type: application/json' \
--data-raw '{
    "url": "https:\/\/google.com",
    "custom": "google",
    "password": "mypass",
    "expiry": "2020-11-11 12:00:00",
    "type": "splash",
    "geotarget": [
        {
            "location": "Canada",
            "link": "https:\/\/google.ca"
        },
        {
            "location": "United States",
            "link": "https:\/\/google.us"
        }
    ],
    "devicetarget": [
        {
            "device": "iPhone",
            "link": "https:\/\/google.com"
        },
        {
            "device": "Android",
            "link": "https:\/\/google.com"
        }
    ],
    "parameters": [
        {
            "name": "aff",
            "value": "3"
        },
        {
            "device": "gtm_source",
            "link": "api"
        }
    ]
}'```
sage otter
#

Do it in your Bot constructor.

winged arch
spring flax
#

can i clone a role

maiden fable
#

!d copy

unkempt canyonBOT
#

Source code: Lib/copy.py

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

Interface summary:

maiden fable
#

Use this ig?

#

!d copy.copy

unkempt canyonBOT
#

copy.copy(x)```
Return a shallow copy of *x*.
maiden fable
#

or uhhh this

quartz badger
#
import requests
from discord.ext import commands

class Money(commands.Cog):
    """Trabalha com a conversão de dinheiro"""

    def __init__(self, bot):
        self.bot = bot

    @commands.command(name = "money", help="Verifica o preço de um par na binance. Argumentos: moeda, base") 
    async def binance(ctx, coin, base):
        
        try:
            response = requests.get(f"https://api.binance.com/api/v3/ticker/price?symbol={coin.upper()}{base.upper()}") 

            data = response.json() 
            price = data.get("price")

            if price: # Se ele achar um preço
                await ctx.send(f"O valor do par {coin}/{base} é {price}")
            else:
                await ctx.send(f"O par {coin}/{base} é inválido.")

        except Exception as error:
            await ctx.send(f"Ups... deu algum erro.")
            print(error)

def setup(bot): #configuração do bot
        bot.add_cog(Money(bot))```
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Money' object has no attribute 'send'

slate swan
#

missed self

quartz badger
#

does anyone know how to solve it?

quartz badger
quartz badger
#

srry for my bad english

slate swan
#

async def binance(self, *args)

quartz badger
slate swan
#

functions in classes always take self as the first parameter

#

before ctx

#

self, ctx, coin, base

quartz badger
slate swan
#

u're welcome

quartz badger
tiny ibex
#

Ok so my bot changes files while running and it's hosted on heroku with github linked but whenever I make a change in the code the files which were generated get deleted. How can I prevent this

slate swan
#

heroku doesn't allow you that

tiny ibex
#

So what should I do?

slate swan
#

don't use heroku?....

tiny ibex
#

So use repl?

slate swan
#

no

tiny ibex
#

So?

slate swan
#

!vps

#

man

tiny ibex
#

I am poor

#

I don't have one😭😭

slate swan
#

sad stuff

winged arch
sage otter
#

The documentation your finding is trash. Discord will disconnect your bot multiple times during its process's lifetime. Causing on_ready to fire multiple times.

winged arch
#

Thank you!

slate swan
#

i have a question how to make xp showin in the rank command cuz i dont know but i need to addd for my leveling system

rare saddle
#

How can you display the name of the rights that are missing?

simple gulch
#

I'm trying to run this (of course with my api key)


headers = {
    'Authorization': 'Bearer APIKEY',
    'Content-Type': 'application/json',
}

response = requests.get('https://short.snowmanking.com/api/account', headers=headers)
print(response.json())```
but I get this error. 
```Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print(response.json())
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/models.py", line 910, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
Why?
sage otter
rare saddle
unkempt canyonBOT
#

When using JSON, you might run into the following error:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This error could have appeared because you just created the JSON file and there is nothing in it at the moment.

Whilst having empty data is no problem, the file itself may never be completely empty.

You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.

Different data types are also supported. If you wish to read more on these, please refer to this article.

unkempt canyonBOT
#

str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
slate swan
#

but i dont know how to make it

rare saddle
winged arch
#

@sage otter Thank you again, I believe i have it cleaned up now ```python

import discord #imports discord.py module, allowing use of their API.
import os #for loading discord token from .env file
from discord.ext import commands, tasks
from dotenv import load_dotenv #for loading dsicord token from .env file

load_dotenv()
token=os.getenv('discord_token') #pulls the discord token from a .env file --

For the bot to launch with this set up, you must have a .env file with the following, excluding quotations "discord_token=DiscordBotTokenGoesHere"

intents = discord.Intents.default() #sets default permissions

client = commands.Bot(command_prefix='!')

discord.Game("Scrabble")

@client.command()
async def ping(ctx):
await ctx.channel.send("pong")

client.run(token) ```

winged arch
#

actually not quite, but i feel like im getting closer lol.

sage otter
rare saddle
sage otter
#

for your case you could do like. ', '.join(error.missing_perms)

simple gulch
#

So what am I doing wrong?
This is the curl code that the website provides to interact with their api.

--header 'Authorization: Bearer tnWzwdnpnaRCkOoW
--header 'Content-Type: application/json' \ ```
```curl --location --request GET 'https://short.snowmanking.com/api/account' \
--header 'Authorization: Bearer tnWzwdnpnaRCkOoW' \
--header 'Content-Type: application/json' \```
So I converted it to Requests like this
```import requests

headers = {
    'Authorization': 'Bearer tnWzwdnpnaRCkOoW',
    'Content-Type': 'application/json',
}
response = requests.post('https://short.snowmanking.com/api/url/add', headers=headers)

response = requests.get('https://short.snowmanking.com/api/account', headers=headers)
print(response.json())```
What am I doing wrong?
slate swan
#

i have a question how to make xp showin in the rank command i mean when sameone types +rank it need shows current rank of user and exp what he gots and he needs to get to another level but i dont know how to make it

#

how do you make a prefix for a server, i have made the command to set it but im not sure at how to make the prefix just for the guild

#

how to take the content of the author's message in the command?

manic wing
manic wing
manic wing
slate swan
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

simple gulch
# manic wing what did it `print`?

I get this. Thats why I was wondering if my conversion wasn't right.

  File "main.py", line 10, in <module>
    print(response.json())
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/models.py", line 910, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
slate swan
#
    ab.close()
    f = open('users.json','r+')
    f.readline()
    if os.stat("users.json").st_size == 0:
      f.write("{}")
      f.close()
    else:
      pass
 
with open('users.json', 'r') as f:
  users = json.load(f)
@bot.event    
async def on_message(message):
    if message.author.bot == False:
        with open('users.json', 'r') as f:
            users = json.load(f)
        await add_experience(users, message.author)
        await level_up(users, message.author, message)
        with open('users.json', 'w') as f:
            json.dump(users, f)
            await bot.process_commands(message)
 
async def add_experience(users, user):
  if not f'{user.id}' in users:
        users[f'{user.id}'] = {}
        users[f'{user.id}']['experience'] = 0
        users[f'{user.id}']['level'] = 0
  users[f'{user.id}']['experience'] += 6
  print(f"{users[f'{user.id}']['level']}")
 
async def level_up(users, user, message):
  experience = users[f'{user.id}']["experience"]
  lvl_start = users[f'{user.id}']["level"]
  lvl_end = int(experience ** (1 / 4))
  if lvl_start < lvl_end:
    await message.channel.send(f':tada: {user.mention} zdobyłeś poziom {lvl_end}. Gratulacje :tada:')
    users[f'{user.id}']["level"] = lvl_end
 
@bot.command()
async def rank(ctx, member: discord.Member = None):
  if member == None:
    userlvl = users[f'{ctx.author.id}']['level']
    await ctx.send(f'{ctx.author.mention} Masz poziom{userlvl}!')
  else:
    userlvl2 = users[f'{member.id}']['level']
    await ctx.send(f'{member.mention} Ma poziom {userlvl2}!') ``` i got something like that
manic wing
slate swan
#

here u are

#

i did this

#

so far @manic wing

rare saddle
#

How can you get an invalid license in another language?

spring flax
slate swan
#

ey @manic wing i sent a my code

maiden fable
spring flax
maiden fable
#

Yea it should

spring flax
#

so what do i do exactly now lol

tawdry perch
maiden fable
simple gulch
# manic wing oh lol, i just replied !json because i saw the error - thats odd

So I had a 503 error was the issue. Now I have a 200 response. But still not sure how to get the data from it? It says it should respond something like

    "error": 0,
    "data": {
        "id": 1,
        "email": "sample@domain.com",
        "username": "sampleuser",
        "avatar": "https:\/\/domain.com\/content\/avatar.png",
        "status": "pro",
        "expires": "2022-11-15 15:00:00",
        "registered": "2020-11-10 18:01:43"
    }
}```
#

but I'm not sure what to do request.?

tawdry perch
simple gulch
#

but not sure where to go from there.

tawdry perch
#

response.json to get that sort of format

simple gulch
#

I tried response.json and it says there isn't anything?

manic wing
#

i thought 200 was an okay

tawdry perch
#

It is

manic wing
#

print(response.text)

simple gulch
#

Oh wait gives this
<bound method Response.json of <Response [200]>>

#

not sure what I typed instead of json last time facepalmz

tawdry perch
#

try ```py
a = response.json
print(a)

manic wing
#

and then you can dict index to it like a normal dict

simple gulch
# manic wing and then you can dict index to it like a normal `dict`

That looks more like it 🙂
{'error': 0, 'data': {'id': 3, 'email': 'email', 'username': 'AnswerBot2', 'avatar': 'https://www.gravatar.com/avatar/6ce01b5db930169803c380739e24e7e8?s=64&d=identicon', 'status': 'free', 'expires': None, 'registered': '2021-12-08 17:38:38'}}
so how would I grab one of those json parts?

peak loom
#

It gives no errors, but it doesn't work.. Here is the code.

#

Slash commands**

unkempt canyonBOT
#

class dict(**kwarg)``````py

class dict(mapping, **kwarg)``````py

class dict(iterable, **kwarg)```
Return a new dictionary initialized from an optional positional argument and a possibly empty set of keyword arguments.

Dictionaries can be created by several means:

• Use a comma-separated list of `key: value` pairs within braces: `{'jack': 4098, 'sjoerd': 4127}` or `{4098: 'jack', 4127: 'sjoerd'}`

• Use a dict comprehension: `{}`, `{x: x ** 2 for x in range(10)}`

• Use the type constructor: `dict()`, `dict([('foo', 100), ('bar', 200)])`, `dict(foo=100, bar=200)`
manic wing
proven aurora
#

need help

#
    @commands.command()
    async def moveall(self, ctx):
        mainVC = ctx.author.voice.channel
        for channel in ctx.guild.channels:
            if isinstance(channel, discord.VoiceChannel):
                for member in channel:
                    #print(f"Moved {member.name} to {mainVC}")
                    await member.move_to(mainVC)```
#

it just doesnt move anyone

rare saddle
#

How can you get an invalid license in another language?

slate swan
#
    ab.close()
    f = open('users.json','r+')
    f.readline()
    if os.stat("users.json").st_size == 0:
      f.write("{}")
      f.close()
    else:
      pass
 
with open('users.json', 'r') as f:
  users = json.load(f)
@bot.event    
async def on_message(message):
    if message.author.bot == False:
        with open('users.json', 'r') as f:
            users = json.load(f)
        await add_experience(users, message.author)
        await level_up(users, message.author, message)
        with open('users.json', 'w') as f:
            json.dump(users, f)
            await bot.process_commands(message)
 
async def add_experience(users, user):
  if not f'{user.id}' in users:
        users[f'{user.id}'] = {}
        users[f'{user.id}']['experience'] = 0
        users[f'{user.id}']['level'] = 0
  users[f'{user.id}']['experience'] += 6
  print(f"{users[f'{user.id}']['level']}")
 
async def level_up(users, user, message):
  experience = users[f'{user.id}']["experience"]
  lvl_start = users[f'{user.id}']["level"]
  lvl_end = int(experience ** (1 / 4))
  if lvl_start < lvl_end:
    await message.channel.send(f':tada: {user.mention} zdobyłeś poziom {lvl_end}. Gratulacje :tada:')
    users[f'{user.id}']["level"] = lvl_end
 
@bot.command()
async def rank(ctx, member: discord.Member = None):
  if member == None:
    userlvl = users[f'{ctx.author.id}']['level']
    await ctx.send(f'{ctx.author.mention} Masz poziom{userlvl}!')
  else:
    userlvl2 = users[f'{member.id}']['level']
    await ctx.send(f'{member.mention} Ma poziom {userlvl2}!') ``` i did this so far @manic wing  sorry for ping
peak loom
slate swan
#
            x = self.cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {msg.guild.id}")
            prefix = x.fetchone()
            prefix = str(prefix)
            await msg.channel.send(f"My prefix for this server is n! and {prefix}")```

sends My prefix for this server is n! and ('{prefix}',)
storm bolt
#

any one can help me ?

peak loom
storm bolt
#

2secs

peak loom
#

1

#

2

slate swan
slate swan
storm bolt
peak loom
#
            
      x = self.cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {msg.guild.id}")
       prefix = x.fetchone()
       prefix = str(prefix)
       await msg.channel.send(f"My prefix for this server is n! and {prefix}")
``` Try that
storm bolt
#

me ?

slate swan
#

alright ty

peak loom
storm bolt
peak loom
peak loom
slate swan
peak loom
slate swan
peak loom
#

Np.

slate swan
#

i am confused

peak loom
slate swan
#

on beta bot it works fine

#

on main bot it doesnt work

#

depress

kindred epoch
#

I have this command where it randomly chooses a time from a list and then sleeps until it finishes but it's not working, any idea why?

#

I have 1,2,3,4 and 5 as seconds in the list

#

But it doesn't work

#

But when l choose a different list with 5 seconds it works

slate swan
#

For some reason this still adds the role id to the json file even if it is not valid?

    @commands.command()
    @has_permissions(administrator=True)
    async def addstaff(self,ctx, role_id=None):
        try:
            role_id = int(role_id)
            role = ctx.guild.get_role(role_id)

            with open("config.json") as f:
                data = json.load(f)

            data["staff-roles"].append(role_id)

            with open('config.json', 'w') as f:
                json.dump(data, f)
            
            success_embed = discord.Embed(title="Staff Role Added", description="You have successfully added `{}` to the list of roles that can run moderation commands!".format(role.name), color=0xD22C45)
            await ctx.send(embed=success_embed)

        except:
            error_embed = discord.Embed(title="Role Error", description="That isn't a valid role ID. Please try again with a valid role ID.", color=0xD22C45)
            await ctx.send(embed=error_embed)
simple kettle
#

I wanted by bot to send a message whenever a certain profile post something on Instagram, I thought webhooks would be the way to go but now I’m not so sure

peak loom
#

It doesn't work, but no errors, can someone help me fix it??????

#

Slash command^

simple gulch
#

hmm. Now I'm getting an error saying I'm not passing the shortened url? This is the full code now.

import requests
from urllib3.exceptions import InsecureRequestWarning

# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)


headers = {
    'Authorization': 'Bearer njcrFyvTspYpWfmU',
    'Content-Type': 'application/json',
}
response = requests.post('https://short.snowmanking.com/api/url/add', headers=headers, verify=False)

data = '{\n    "url": "https:\\/\\/google.com",\n    "custom": "google",\n    "password": "mypass",\n    "expiry": "2020-11-11 12:00:00",\n    "type": "splash",\n}'

response = requests.post('https://short.snowmanking.com/api/url/add', headers=headers, data=data, verify=False)
data = response.json()
print(data)```
Here is the error
```py
{'error': 1, 'message': 'Missing required parameter: url'}```
#

Isn't the URL being passed? Under Data?

kindred epoch
peak loom
slate swan
#

how do you check if there is more after a mention

if self.bot.user.mentioned_in(msg):```
peak loom
#

That's bulls*****it

sage otter
#

Alternatively use fetch_user()

slate swan
warm goblet
#

newone = '111 - 222'
newone = my_string.partition("- ")[2]

Output : 222

#

How do I get the output to be 111?

slate swan
cloud dawn
#

Cursor is basically the connection, yeah if it not used for half an hour close it but else it's best to let it stay open.

slate swan
#

No

#

Cursor is not the same as a connection.

#

When you are done using the cursor, close it. Simple rule.

#

If you don't agree, search it up and everyone else does agree.

cloud dawn
#

Your right mb, i don't use cursors anyways lol

kindred epoch
slate swan
#

how do you check if there is more after a mention

if self.bot.user.mentioned_in(msg):```
sage otter
#

!d discord.Message.mentions ?

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

slate swan
frozen ferry
#

Hey everyone, does anyone know a good place to learn the python discord library? I'm kinda stuck with just the official documentation.

dapper cobalt
# frozen ferry Hey everyone, does anyone know a good place to learn the python discord library?...

I've made a few examples. However, it's using a fork called disnake. You can check it out. https://github.com/ScopesCodez/disnake-examples

GitHub

Examples you can use whether in disnake.py (https://pypi.org/project/disnake/) or discord.py (https://pypi.org/project/discord.py/) - GitHub - ScopesCodez/disnake-examples: Examples you can use whe...

sick birch
#

I also had some fun looking at RoboDanny’s source code (discord bot made by the creator of discord.py)

frozen ferry
#

Thanks a lot for the advice, guys < 3

slate swan
#

how do you do redirect_uri in OAuth

untold token
#

The disnake repository has ones that are good too

dapper cobalt
untold token
#

and there is a WIP guide

untold token
#

Like type hintings, docstrings etc etc

slate swan
#

I am trying to make a command that changes the prefix of the bot but I am really struggling. How do I replace something in json, this is what I have so far.

    @commands.command()
    async def prefix(self,ctx,prefix):

        with open('config.json') as f:
            data = json.load(f)
    
        valid_user = False

        for role_id in data["staff-roles"]:
            try:
                if ctx.guild.get_role(role_id) in ctx.author.roles:
                    valid_user = True
            except:
                pass
    
        if valid_user or ctx.author.guild_permissions.administrator:
            with open('config.json') as f:
                data = json.load(f)
```json file:
```json
{"staff-roles": [], "prefix": ".", "verified-roles": []}
brave vessel
#

!e
JSONs in Python are parsed into a 'dictionary'
With those you can change key/value pairs, so say we have the dictionary:

my_dict = {"staff-roles": [], "prefix": ".", "verified-roles": []}
# to change prefix to ','
my_dict["prefix"] = ","

print(my_dict)
unkempt canyonBOT
#

@brave vessel :white_check_mark: Your eval job has completed with return code 0.

{'staff-roles': [], 'prefix': ',', 'verified-roles': []}
brave vessel
#

Then, you can just rewrite the file

slate swan
#
def get_prefix(bot,message):
    try:
        db = sqlite3.connect("Config.db")
        cursor = db.cursor()
        x = cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {message.guild.id}")
        a = x.fetchone()
        if a == None:
            return
            commands.when_mentioned_or("n!")(bot,message)
        else:
            return commands.when_mentioned_or(a[0],"n!")(bot,message)```

when you @ the bot and use a command it sends the command twice
brave vessel
slate swan
#

Well first things first, don't always connect to the database.

#

As for every message you make a new connection and new query, which is pretty bad.

slate swan
#

Don't think so, but at least latency and other issues you will face in the future.

brave vessel
# slate swan im not

You might think you're not, but that's happened to me before too. I think usually it's solved with just completely shutting down the program with whatever you're running it on and then restarting it

brave vessel
#

ah

slate swan
#

its quite weird

royal jasper
#

hey! i need to check if user has role... How can i do it?

brave vessel
royal jasper
brave vessel
#

If it's the latter, something like:

role = discord.utils.get(ctx.guild.roles, name="Role name goes here")
# if you know the member you want to check the role from
if role in member.roles:
  # code goes here
royal jasper
#

ty dude

brave vessel
#

np :D

slate swan
#

@brave vessel do you have a idea on why it comeds back 2 times?

brave vessel
brave vessel
pale turtle
#

Yeah?

brave vessel
#

Ah, you could do that, I'm mostly used to the name kwarg though

#

it'll probably save some time though

pale turtle
brave vessel
#

you could just replace member with user if you already defined uesr

royal jasper
#

i want to the member type !config and then the bot gives a role

brave vessel
#

wdym?

brave vessel
# pale turtle I mean using guild.get_role

Ah, I mean you could, but would that work cross-server? Like I know quite a few bots auto-create a Muted role I think and check for that role via a name because the ID won't be consistent cross-server

This is a genuine question btw, not sure

#

oh does guild.get_role support the name of the role?

#

guessing not actually

royal jasper
pale turtle
brave vessel
#

^ it will

slate swan
#

sends 2x

brave vessel
# slate swan sends 2x

ohh, the colors of the embed are different, are you running something twice internally?

pale turtle
#

My bad

brave vessel
brave vessel
slate swan
#

@brave vessel no i forgot its random

brave vessel
#

ah

slate swan
#

this is a different command

pale turtle
#

Try to shut down your bot and re-run

slate swan
pale turtle
#

The best way I use is to reset the token

slate swan
#

its still happening

pale turtle
#

Mmm

#

Weird

slate swan
#

yeah very

pale turtle
#

Maybe you are running it from multiple instances by accident?

slate swan
#

tried that

#

its really annoiyng

velvet tinsel
#

Show code

slate swan
# velvet tinsel Show code

okay here

def get_prefix(bot,message):
    # try:
    db = sqlite3.connect("Config.db")
    cursor = db.cursor()
    x = cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {message.guild.id}")
    a = x.fetchone()
    a = a[0]
    return commands.when_mentioned_or(a,"n!")(bot,message)
    # except Exception as E:
    #     print(E)
    

client=commands.Bot(command_prefix=get_prefix, case_insensitive=True, intents=discord.Intents.all(),help_command=None)```
velvet tinsel
#

Your command was prefix

slate swan
velvet tinsel
#

What’s get_prefix

slate swan
velvet tinsel
#

Is it an alias?

pale turtle
#

I doubt the problem is with the command itself

slate swan
slate swan
# velvet tinsel What’s get_prefix
def get_prefix(bot,message):
    # try:
    db = sqlite3.connect("Config.db")
    cursor = db.cursor()
    x = cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {message.guild.id}")
    a = x.fetchone()
    a = a[0]
    return commands.when_mentioned_or(a,"n!")(bot,message)
pale turtle
#

You both talk about different things, @slate swan he wanted you to send the prefix command

velvet tinsel
#

yes

pale turtle
velvet tinsel
#

Your function was get_prefix

slate swan
#

bet but it happens on all commands

velvet tinsel
#

The command was prefix

slate swan
#

happens on all commands tho

pale turtle
velvet tinsel
slate swan
#

yeah

slate swan
velvet tinsel
#

Ok

#

Oh no db

#

Show db?

slate swan
slate swan
velvet tinsel
#

errrr

#

I know nothing about databases

#

Never really learned them

slate swan
pale turtle
#

Try to use a print statement in the command

#

Wait nvm it doesn't matter really

#

Oh wait

#

You are using cogs right?

slate swan
#

yeah

pale turtle
#

You use on_message?

#

For cog listener

slate swan
slate swan
pale turtle
#

Inside the cog?

velvet tinsel
pale turtle
#

Not good, listeners don't need it

slate swan
velvet tinsel
#

😭

slate swan
pale turtle
#

Cog.listener is a listener, you shouldn't use process_commands in it

velvet tinsel
#

Why are the colors different

slate swan
#
 @commands.Cog.listener()
    async def on_message(self,msg):
        if msg.author == self.bot:
            return
        if self.bot.user.mentioned_in(msg):
            try:
                x = self.cursor.execute(f"SELECT prefix FROM config WHERE guild_id = {msg.guild.id}")
                prefix = x.fetchone()
                embed=discord.Embed(title="", description=f"My prefix for this server is `n!` and `{prefix[0]}`", color=discord.Color.blurple())
                # await msg.channel.send(embed=embed)
                

            except AttributeError:
                embed=discord.Embed(title="", description=f"My prefix is `n!`", color=discord.Color.blurple())
                await msg.channel.send(embed=embed)
            await self.bot.process_commands(msg)
            return```
velvet tinsel
#

Just wondering

slate swan
pale turtle
#

You only need it in on_message event

#

Not listener

slate swan
#

process_commands?

pale turtle
#

Delete await self.bot.process_commands(msg)

slate swan
#

okay

pale turtle
#

And than retry

slate swan
#

omg it works tysm

pale turtle
#

Np

slate swan
velvet tinsel
#

The moment where this channel goes quiet

pale turtle
quartz anchor
#

How can I get started on python? i want to learn python to program my bot in discord Discord.py

NOTE: I'm Brazilian but I understand English

slate swan
velvet tinsel
#

I don’t do discord nowadays

pale turtle
#

!resources will help you understand Python basics and everything you need for discord.py. Than I would suggest looking at discord.py documentation, GitHub code examples, and this tutorial: https://vcokltfre.dev
NOTE: discord.py is an advanced lib, envolving advanced Python and complicated codes, you SHOULD learn basic and more then mediocre Python to start discord.py.
Good luck!

A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

velvet tinsel
#

I’m trying to upload something to GitHub

quartz anchor
royal jasper
#

i want to check if the user has a role. if it has this role the bot should not say anything, but if it does not, the bot will speak a text... how can i do this?

velvet tinsel
#

Why do people call me download

quartz anchor
velvet tinsel
#

I'll change my name

quaint epoch
#

How to check if a message pinged my bot?

velvet tinsel
manic wing
unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

sick birch
quaint epoch
sick birch
#

ctx.message.mentions()

pliant gulch
#

It's an attribute

quaint epoch
#

im confused

#

i just want to know if the message, contains my ping

cedar stream
#

If ping in message.mentions

sick birch
#

i think i was getting it confused with the member.mentioned_in()

quaint epoch
sick birch
#

a member object

quaint epoch
#

okay

cedar stream
#

Look in the docs

quaint epoch
cedar stream
slate swan
#

@bot.command()
async def _play(ctx):
if not ctx.author.voice:
return await ctx.send("You are not commected")

Why this dont work for lavalink

cedar stream
#

Try to rename it

slate swan
slate swan
cedar stream
#

Da

slate swan
#

Lol
Ma brate lavalink je bot ne senda message kad kucas $p i kad nisi u voice

#

Ne pise kao
You arw not connected in voice

#

Valjd vidis code sto sam poslao 😂

cedar stream
#

Ja ker maš že command play

#

2x

#

Preimenuj play command

cedar stream
#

Command play alr exist etc.

slate swan
#

Pa znam da to pise ali kako mogu nap

cedar stream
#

Samo preimenuj komando

#

Namesto play probaj play_music samo da vidiš če dela

slate swan
#

Radi idemo dalje xd

cedar stream
#

Ne dela?

#

A dobiš error?

slate swan
#

Da

cedar stream
#

Isti ko prej?

slate swan
#

Da

cedar stream
#

Kak to

#

Daj pošlji screen shot

cedar stream
#

Od kode

pale turtle
#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

pale turtle
#

Ahh what is the speak English in the server

#

Anyway you get the idea

cedar stream
slate swan
#

what are all of the channel permissions

#

the new ones

cedar stream
#

?

slate swan
cedar stream
#

Oh, I think It’ s named same as in discord

slate swan
#

tysm

cedar stream
#

Np

wet cargo
#

I need the python code for command where are two arguments, first arg1 is to choose one option from the list, second arg2 is to put value by the user (from the screen opcje = options; obliczanie = calculation; mnożnik = multiplier; wartość = value). Than bot will calculate (arg1 * arg2) and return result for the user. I can PAY if someone learn me how to code this.

#

I need the python code for command where are two arguments, first arg1 is to choose one option from the list, second arg2 is to put value by the user. Than bot will calculate (arg1 * arg2) and return result for the user. I can PAY if someone learn me how to code this. I can sand a photo of this in private chat.

sick birch
#

What do you mean by "value by the user"?

#

Not sure if slash commands let you enter in text

#

Never mind it has a STRING type

ebon island
#

Is it possible to create a loop that checks for whether or not a message is actually sent and retry until it is?

sick birch
#

if the message isn't sent you'll get an error

ebon island
#

It doesn't seem to be an error which is picked up by Python though

sick birch
#

sending a message can raise one of 3 exceptions:

#

if you don't get any of these, then the message is sent

#

If you don't get an error and the message isn't sent, you have a faulty error handler.

ebon island
#

So the error resulting (presumably from connection issue) is as such:

Task exception was never retrieved

Functionally, each server has a task object which then replaces itself with the next task barrel of monkeys style, the problem is, when a connection issue arises it effectively loses the chain and doesn't have an error and instead simply stops trying to continue

sick birch
#

Can you send the full traceback?

placid meadow
#

I want to delete the info of the server in the .json via the command...

ebon island
#
Task exception was never retrieved
future: <Task finished name='Task-5818' coro=<BarBot.take_turn() done, defined at /app/cogs/barbot.py:167> exception=DiscordServerError('503 Service Temporarily Unavailable (error code: 0): <html>\r\n<head><title>503 Service Temporarily Unavailable</title></head>\r\n<body bgcolor="white">\r\n<center><h1>503 Service Temporarily Unavailable</h1></center>\r\n<hr><center>cloudflare-nginx</center>\r\n</body>\r\n</html>\r\n')>
Traceback (most recent call last):
  File "/app/cogs/barbot.py", line 171, in take_turn
    await self.pass_the_mic(server)
  File "/app/cogs/barbot.py", line 179, in pass_the_mic
    await server.approved_channel.send(f':microphone2: **Pass the Mic!**')
  File "/usr/local/lib/python3.9/site-packages/discord/abc.py", line 1065, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
  File "/usr/local/lib/python3.9/site-packages/discord/http.py", line 252, in request
    raise DiscordServerError(r, data)
discord.errors.DiscordServerError: 503 Service Temporarily Unavailable (error code: 0): <html>
<head><title>503 Service Temporarily Unavailable</title></head>
<body bgcolor="white">
<center><h1>503 Service Temporarily Unavailable</h1></center>
<hr><center>cloudflare-nginx</center>
</body>
</html>

Returned error there is 503 Service Temporarily Unavailable, is this something you can target with try except?

sick birch
#

Ah that sounds like a server issue

pliant gulch
#

This has nothing to do with your bot, just a discord end error

#

Nothing you can do to fix until discord fixes their issue

sick birch
#

Perhaps implement an exponential backoff algorithm

#
  • try to send message
  • if it doesn't work, wait 2 seconds
  • try to send message
  • if it doesn't work, wait 4 seconds
  • try to send message
  • if it doesn't work, wait 8 seconds
  • try to send message
  • if it doesn't work, wait 16 seconds
  • try to send message
  • if it doesn't work, wait 32 seconds

so on and so forth

ebon island
#

Interesting, so how would I go about actually implementing that?

#

Given that the tasks are effectively an attr on an Object, how do I handle that spawning/retry?

sick birch
#

Have a class that has the last wait time stored in memory, each time you call a certain method, double it, and return it while you also store the new doubled number in memory

#

I've seen this actually implemented in the discord.py library's source code itself

ebon island
#

Really? Whereabouts?

#

That would be extremely helpful to see

sick birch
#

I really wish I could tell you but frankly it was a while ago and I don't exactly remember

pliant gulch
#

Its done inside of run

sick birch
#

I actually thought it was hidden away as a class in some arbitrary file but nope, here we are haha

ebon island
#

Ooh, interesting! I see this is in the official Discord.py git, does that mean it is something accessible from the Discord.py package?

sick birch
#

No it's mostly used within the internals

#

I doubt it was meant for use, but with some tweaking you could probably get it to work

#

though i'd have to suggest you replicate the class yourself, simplify it down perhaps, and use that instead

ebon island
#

Is there any way to invoke it? It doesn't seem that however it is internally implemented that it is working in our case

sick birch
#

I mean it's just a class so perhaps you could just import it and call its methods

#

But yet again it wasn't designed for front end use, so who knows what it might break

#

It has a lot of elements to it that aren't really needed for regular use (very in-depth type hinting, more functionality than you would need for a simple backoff algo)

#

you could strip it down to a very simple class that works efficiently

ebon island
#

I think the first thing I will try is just a linear retry loop in a very simplified command set, just a simple loop that does try except and if there is ever a service unavailable it passes the command into it and also passes the wait time into the method as args

sick birch
#

Sound alright

ebon island
#

what is the actual exception in Dpy?

sick birch
#

What do you mean

ebon island
#

the Exception

sick birch
#

For sending a message?

ebon island
#

assuming it's a built in exception

#

503

pliant gulch
sick birch
#

Oh 503 is a HTTPException or something of that sort

pliant gulch
#

No

#

Well, yes ig

#

But its a server error

#

Something went wrong with discord's servers and their offline

sick birch
#

Right it should raise a discord.HTTPException though?

pliant gulch
#

It subclasses HTTPException iirc

ebon island
#

ooh okay, let me look in the docs at HTTPException and see if there is a special case handled for that

sick birch
#

pretty sure the error has .status attribute

placid meadow
#

The first one add a channel , i want the second too remoove the channel.

#

help please

ebon island
#

Yeah!

#

Hmm

sick birch
#

you can just check if the .status == 503 or something of that sort to check for an outage, if so start the exponential/linear backoff algorithm

pliant gulch
#

You probably want the code attribute of the error

#

That's the discord specific error code, althought it might be the status

sick birch
ebon island
#

I will do some testing and see what I can make happen 🙂

sick birch
#

awesome, best of luck

ebon island
#

Thank you so much! ❤️

pliant gulch
#

And for an outage check you can just check if the error code starts with 5

#

Cause anything from discord that is a 5xx error is a server error

sick birch
#

str(code)[0] == "5" hehe

#

or floor it

placid meadow
#

anybody no?

sick birch
# placid meadow anybody no?

json.dump() will only dumb the dict contents to the json file, just remove the channel from the dict and dump that

placid meadow
#

i want it to be remoove via command

#

as my bot is a global chat

sick birch
#

What is the structure of your JSON file?

placid meadow
#

guild id
channel id
invite

sick birch
#

Are they seperated into nested dicts?

placid meadow
sick birch
#

I see

#

It would probably be a better idea to use the guild ID as the key to the nested dict

#

would be easier to remove

placid meadow
#

sure i don't mind

#

but how to do hmm

sick birch
#

with your current structure it's going to get really messy and unconventional to remove a certain guild

magic ore
#

using an actual database would make this much easier

sick birch
#

yikes

#

but yes use an actual database

#

json as a db is a terrible idea

placid meadow
#

right , but i have an actual server to host it

#

has more than 2tb of storage

sick birch
#

Awesome, put something like postgres or MySQL on it

placid meadow
#

no idea how to set it up tho

sick birch
#

sqlite is very easy to setup and lightweight

#

it's just a .db file

placid meadow
#

as oppose to a .json?

sick birch
#

right, except it's a full fledged database

#

.json on the other hand, is only a file format

#

it's terrible at storing persistent data

#

due to sqlite's speed and lightweight-ness, many people even use it as a caching layer for their real databases

placid meadow
#

okok i see letm e download really fast

pliant gulch
#

Ehhh I wouldn't really recommend sqlite as a cache for your database

#

If you want a good cache you'd want to use redis

#

Caching stuff is usually for scalability and redis just crushes that

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'check' is not defined?

sick birch
placid meadow
#

@sick birch

sick birch
#

...def?

placid meadow
#

def?

sick birch
#

the file extension

placid meadow
sick birch
#

correct me if i'm wrong here but sqlite will auto generate the file if you try to connect to a file that doesn't exist

#

not sure if you should make a .db file by hand as sqlite might fill it up with some sort of formatting data

placid meadow
#

it does make a database file

#

but can't open it

sick birch
#

why not?

#

also you can't manually open it without specialized software

placid meadow
#

oh

#

wich software can i use?

sick birch
#

there are plenty out there, a quick search for sqlite database browser will reveal many

#

or you can just print it out using python to the terminal

pliant gulch
#

Once you get sqlite setup you want to make sure you are using an async driver, since discord.py is an asynchronous environment

sick birch
#

^ like asqlite or aiosqlite

#

asqlite was actually made by Danny (creator of discord.py), it has better defaults and is lightweight so i would suggest that

slate swan
#

how can I find a role ID from the role name

sick birch
#
discord.utils.get(...).id
kindred drum
sick birch
#

No, refer to the documentation

#

discord.utils.get(...) takes an iterable and kwargs

cloud tundra
#

Hi
I need some help for my bots queue function

#

can someone help?

sick birch
#

sure just ask

cloud tundra
#

im trying to make a queue function for the bot

#

and i need to await a function using lambda

#

the function that leads to the queue, playing the next song

#

but im getting errors

sick birch
#

you don't need a lambda

#

you can pass in a coro just as well to the after function

#

or i think