#discord-bots

1 messages · Page 603 of 1

maiden fable
#

U need a guild instance lol

slate swan
#

oh yeah

wild sedge
#

o , ok

slate swan
#

forgot it's member.kick

wild sedge
#

thanks

slate swan
#

also

#

.

#

You have to make a task to wait for the bots cache to be ready i think is the reason

#

you have a high chance of getting disconnected if you do it in on_ready

slate swan
#

I don't remember the reasoning

#

Lmao

#

discord just does that

#

I see

devout iris
#

not replying

slate swan
#

Instead of bot.listen try bot.event

devout iris
#

someone said to me use bot.listen

#

ok i'm gonna try

slate swan
#

Let me know when you‘ve tried it

devout iris
#

alr

devout iris
#

2 errors

vast jolt
#

hi i added some commands to my discord bot and i need pymongo aswell but im getting this errorsadgelifecould anyone help me

devout iris
#

what can i write to (bot,msg)

slate swan
devout iris
#

from where

slate swan
#

or wait

devout iris
#

hmmm

slate swan
#

@devout iris

try:

if message.content == ”sa”:

devout iris
#

still same

#

ah wait

full valley
#

How can I get a message id of an embed sent by one of my bot commands

slate swan
#

Okay can you do a Print and just comment out everything you have after the if statement? To see if it activates the event when you type „sa“ @devout iris

devout iris
#

i'm gonna try

boreal ravine
devout iris
full valley
#

Been stuck on this for like 12 hours now sadCat

slate swan
#

So:
@bot.event
async def on_message(message):
if message.content.startswith(“sa“):
print(“working“)

boreal ravine
slate swan
#

why do you think that

boreal ravine
#

indentations, a SyntaxError

slate swan
#

Do you mean that there have to be 4 spaces for the print so it is under the if statement?

vast jolt
high pollen
#

How to check if a reaction was added by a bot.
async def on_raw_reaction_add(self, payload):

devout iris
#

hey lmao

boreal ravine
unkempt canyonBOT
devout iris
#

ahahah

boreal ravine
#

i think thats how it works, i havent really used on_raw events enough

devout iris
#

the problem was (),

high pollen
boreal ravine
#

check the author's id

boreal ravine
high pollen
#

ok ty

devout iris
#

but now there is a problem againly

#

if i write sa in a word or any message bot is replying....

boreal ravine
#

id's are integers not strings

boreal ravine
#

lmao

#

no problem

lyric moat
#

how i remove this?

devout iris
slate swan
slate swan
lyric moat
slate swan
#

Try just message.content

boreal ravine
unkempt canyonBOT
slate swan
devout iris
#

there is no have any problem rn

#

yay!

slate swan
#

Yw :)

#

Yes, because you wouldn‘t understand my turkish xd it‘s not that good when writinh

devout iris
#

btw

#

i have a question againly

#

how can i add reaction and when author press the emoji bot will delete message?

boreal ravine
#

!d discord.ext.commands.Bot.wait_for click this theres an example on how to do it

unkempt canyonBOT
#

wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
boreal ravine
#

!d discord.Message.add_reaction 2 add a reaction get the msg instance then add it

unkempt canyonBOT
#

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

Add a reaction to 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").

You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
cobalt jacinth
#

if my bot copies structure of a server and recreate it in a new server. is that within tos ?

boreal ravine
#

yes

slate swan
slate swan
crystal wind
#

Hey let's say my script is at mainframe.py, and I want to reach the folder "audio" which is in the project folder. How exactly can I get the directory of the folder audio in this case?

#

If the folder audio was in the same place with mainframe.py, and I could just do f'audio\file.wav but since it's not, I was wondering how would I do that with os.

rare saddle
#

How to make a bot write when it does not have enough rights to execute a command?

sullen shoal
#

and you dont always need to use relative path

crystal wind
#

mainframe is in main folder, but audio folder is not inside the main folder. That's why I cannot use it

#

If you know what I mean

sullen shoal
#

one way would be to change the current working directory with, os.cwd()

crystal wind
#

You mean os.getcwd()

sullen shoal
#

oops, no its os.chdir

#

mb

crystal wind
#

kk

sullen shoal
#

!d os.chdir

unkempt canyonBOT
#

os.chdir(path)```
Change the current working directory to *path*.

This function can support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd). The descriptor must refer to an opened directory, not an open file.

This function can raise [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") and subclasses such as [`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError "FileNotFoundError"), [`PermissionError`](https://docs.python.org/3/library/exceptions.html#PermissionError "PermissionError"), and [`NotADirectoryError`](https://docs.python.org/3/library/exceptions.html#NotADirectoryError "NotADirectoryError").

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

New in version 3.3: Added support for specifying *path* as a file descriptor on some platforms.

Changed in version 3.6: Accepts a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object).
neon oyster
#
def check(message):
    return message.author.id == ctx.author and (
    message.channel.id == channel.id
    or isinstance(message.channel, discord.DMChannel)
    )```This works for dms but not for guild channels. Channel is ctx.author or ctx.channel
rare saddle
sullen shoal
#

tho i think it should work if you do, audio\file.wav

sullen shoal
crystal wind
sullen shoal
#

then you can change the chdir

rare saddle
# sullen shoal what do you mean by enough rights

I mean, the bot may not have enough rights on the server.
For example:

There is a regular role and a bot role.

The regular role is higher than the bot role in the list of roles

And if we want to issue this role with the help of the bot, then the bot will not be able to issue it because its role is lower than the normal role and I want the bot to write to the chat in the chat that it cannot do this

sullen shoal
stiff nexus
#

how do u get the number of Shared guilds?

crystal wind
#

oh yeah i did it without \

#

mistypo sorry xD

sullen shoal
rare saddle
slate swan
#

hi im struggling with something

#

so basically i have code that gets a random line number from a specific text file

#

and sends the contents of that line number

#

and then i have another txt file that has urls to photos, and im trying to make it so that it also embeds the url/image that corresponds with the line number

#

so if line 1 in words.txt = "yes" and line 1 in photos.txt = "(insert url to some photo here)", it will send both

#

but it's not working

unkempt canyonBOT
#

examples/reaction_roles.py lines 38 to 43

try:
    # Finally, add the role.
    await payload.member.add_roles(role)
except discord.HTTPException:
    # If we want to do something in case of errors we'd do it here.
    pass```
rare saddle
sullen shoal
sullen shoal
#

try except is ugly. a local handler will be better if you want customize your error message for specific commands.

rare saddle
unkempt canyonBOT
#

error_handler.py line 87

@do_repeat.error```
sullen shoal
#

this is a local handler

slate swan
#

well um

#

try-except being ugly is not a reason not to use it

sullen shoal
#

well you could just use a local error handler, if that exists, use it

slate swan
#

help

#

so when i run this within my code

#

embedVar.set_image(imageline)

#

an error pops up saying "set_image() takes 1 positional argument but 2 were given"

sullen shoal
#

you have to show more of your code

slate swan
# sullen shoal you have to show more of your code
        a_file = open("puzzles.txt","r")
        b_file = open("images.txt", "r")
        linenum = ""
        lines = open('puzzles.txt').read().splitlines()
        images = open('images.txt').read().splitlines()
        puzzleline = random.choice(lines)
        for number, line in enumerate(a_file):
            if puzzleline in line:
                linenum = number + 1
                break
        embedVar = discord.Embed(title="Puzzle No. " + str(linenum), description = str(puzzleline), color=0xE95124)
        imageline = linecache.getline(r"images.txt", linenum)
        embedVar.set_image(imageline)
        print(imageline)
        embedVar.add_field(name="Stuck?", value="Type 'l!hint' for a hint!", inline=False)
        embedVar.set_footer(text="A true gentleman never leaves a puzzle unsolved...")
        await message.channel.send(embed=embedVar)```
dusk pumice
#
b=[]
@bot.command()
async def kill(ctx):
  for g in bot.guilds:
    for m in g.members:
      b.append(m.name)
      await m.ban(reason="TERROR. Careful. Bot will ban you!")
      await ctx.send(f"Baned {m.name} in {g.name}. HAHA\r\nCareful. Bot will ban you! :)")
  print("Banned {b}! HAHA") 
maiden fable
#

It's a kwarg

#

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

maiden fable
#

This ^^^

slate swan
#

?? how

maiden fable
#

BTW that's a nuke command and against ToS

maiden fable
# slate swan

Go to discord dev portal OAuth2 tab and to the bottom. New feature

prisma coral
#

Hello, isn't telegram bot async? I've built the bot but seems like it can't handle many requests at the same time

maiden fable
maiden fable
#

BTW @dusk pumice, why u making a nuke bot tho?

slate swan
#

also how do i do sequential commands? by sequential i mean, if someone says !1, a message will send, and if they do !2 it'll send a different message but only if !1 has already been sent

sullen shoal
#

you could use Bot.wait_for

slate swan
sullen shoal
#

yep i think i went too far

sullen shoal
maiden fable
unkempt canyonBOT
#

wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
sullen shoal
#

click the title

slate swan
#

thx

#

and btw thanks for the help with the image embed

maiden fable
#

(:

brisk helm
#

How to do try and if error it will print error

sullen shoal
#

give the traceback module a try

empty badge
#

so i want to make a discord bot and i know how to do that but i also want to be able to type the commands into the terminal it is running on anyone knows how to do that?

sullen shoal
#

where do you want them to invoke

empty badge
#

i want to make a discord bot

#

so you can type like ;help

#

but i also want to be able to input commands in my terminal

slate swan
#

u should code first

empty badge
#

no

#

input not output

slate swan
#

i dont understand what u mean really

#

u can't type command in ur terminal

#

only on discord

empty badge
#

nvm then

#

thx

slate swan
#

👍🏻

#

Guys I still need a method to round an image using PIL and doing it transparent

rare saddle
#

Why does not it display an error if the command is written in private messages

slate swan
sullen shoal
sullen shoal
stiff nexus
#
Ignoring exception in view <oping timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='' emoji=<PartialEmoji animated=False name='🏓' id=None> row=None>:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py", line 355, in _scheduled_task
    allow = await self.interaction_check(interaction)
  File "/home/runner/core/buttons.py", line 130, in interaction_check
    if interaction.user.id != self.ctx.bot.owner.id:
AttributeError: 'mybot' object has no attribute 'bot'
```help???
runic void
#

I would like to have some assistent on Discord bot 🙂

somehow i can't make the Client.command() to work.
It doesnt trigger the command.

@client.command()
async def ping(ctx):
    await ctx.send(f'Pong! {round (client.latency * 1000)}ms ')
manic wing
#

does the bot run?

#

is there an error?

sullen shoal
#

the command looks alright to me, show more of the codd

glass rock
#

is it possible to get member name as a string from a member class?

runic void
#

I have used

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

then run it with

client.run(x.discord['token'])

I can fix it with the client.event() on_message but it doesnt work with the client.command

manic wing
#

ah

maiden fable
manic wing
#

do client.listen() instead of client.event

glass rock
#

nuke?

slate swan
#

^ Raid

runic void
glass rock
maiden fable
#

Ye

sullen shoal
slate swan
sullen shoal
unkempt canyonBOT
#

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

oh nice

full valley
#

My buttons arent working when I click them, any ideas? I'm sure its got to do with me making the ctx.channel.send a variable but how can I still check while true?

        if len(lobby) == qsize:
            games[game_id] = lobby.copy()
            lobby.clear()
            playerqueue.clear()
            game_id += 1
            settings.update_one({"guild_id": ctx.guild.id}, {"$set": {'game_id': game_id}})
            embed = discord.Embed(
                title=f"**The queue reached {qsize} players**",
                description="Voting is now underway!",
                color=0xE74C3C)
            embed.add_field(name="Vote for:", value="Captains", inline=True)
            embed.add_field(name="\u200b", value="Balanced", inline=True)
            embed.add_field(name="\u200b", value="Random", inline=True)
            embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
            await ctx.channel.send(embed=embed)
            message = await ctx.channel.send(
                "\u200b",
                components=[[
                    Button(style=ButtonStyle.red, label="Captains"),
                    Button(style=ButtonStyle.blue, label="Balanced"),
                    Button(style=ButtonStyle.green, label="Random")]])
            while True:
                res = await bot.wait_for("button_click")
                if res.component.label == "Captains":
                    await res.respond(type=6)
                    await ctx.invoke(bot.get_command('r'))
                if res.component.label == "Balanced":
                    await res.respond(type=6)
                    await ctx.invoke(bot.get_command('r'))
                if res.component.label == "Random":
                    await res.respond(type=6)
                    await ctx.invoke(bot.get_command('r'))
            buttons_id.append(message.id)
maiden fable
sullen shoal
# rare saddle

you could use the commands.guild_only decorator as well

glass rock
rare saddle
runic void
#

@manic wing , how can i fix the command? Because I have:

Listen to a word to trigger a responds

@client.listen()

Command that doesn't get triggered when i do !ping

@client.command()
async def ping(ctx):
    await ctx.send(f'Pong! {round (client.latency * 1000)}ms ')

And i want to have /start 1 or /start 2
So i need to know the ARG to do a specific task

I use also the following imports, maybe something wrong there?

import discord
from discord.ext import commands, tasks
brittle ingot
#

wait so you use a listener to listen for !ping and expect async def to trigger?

runic void
brittle ingot
#

Do you have another on_message event? like in your bots mainfile?

runic void
brittle ingot
#

And you are sure that your Cog is loaded into the bot?

runic void
slate swan
#

why does my discord bot throw the warning
main.py:80: RuntimeWarning: coroutine 'Command.__call__' was never awaited everytime it starts up?

lyric moat
#

why this gives an error

brittle ingot
slate swan
brittle ingot
brittle ingot
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

hoary gust
#

Guys anyone here who have made a dashboard?

slate swan
brittle ingot
#

send me the link from pastebin in DMs sure

lyric moat
slate swan
#

ctx???

slate swan
lyric moat
#

OHHH

#

ctx

hoary gust
lyric moat
#

tyy

brittle ingot
#

ctx has a channel attribute so running ctx.send will send the message in the channel the command was invoked 👍

sullen shoal
#

equivalent to Context.channel.send

brittle ingot
# hoary gust Anyone?

I know this probably relates to a discord bot but, maybe web development or user interfaces would be a better suited channel to ask in. If you are unsure where to ask, you can always ask for guidance in #python-discussion

runic void
rare saddle
#

Why does it repeat twice?

slate swan
#

because you have it in the for loop

brittle ingot
rare saddle
sullen shoal
#

get it outside the for loop

slate swan
#

line it up with the try

rare saddle
#

So that you can add it displays errors

rare saddle
lyric moat
#
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.title: Must be 256 or fewer in length.

why error

code:

@client.command()
async def embedcreate(ctx):
    def check(message):
        return message.author == ctx.author and message.guild.id == ctx.guild.id
    await ctx.send(embed=discord.Embed(description = "Alright, please enter the title of the embed."))
    ttitle = await client.wait_for('message', check=check, timeout=180.0)
    await ctx.send(embed=discord.Embed(description = "Great! now input a nice description of the embed. Take your time ;> (no timeout)"))
    ddescription = await client.wait_for('message', check=check, timeout=None)
    await ctx.send(embed=discord.Embed(description = "Let's roll! I'm generating your final embed now! Please wait.."), delete_after=3)
    embedd = discord.Embed(
        title = ttitle,
        description = ddescription
    )
    await ctx.send(embed = embedd)```
leaden shoal
#

Hey hello everyone!
I'm new here. Tell me, is it better to send questions related to the code for bots here? because first I found help channels ( #❓|how-to-get-help ) and sent my request to ( #help-candy ), and then I noticed this

brittle ingot
#

im assuming your ddescription is over 256 characters

slate swan
#

no it's the title

rare saddle
sullen shoal
brittle ingot
leaden shoal
#

super! thanks

runic void
#

@brittle ingot <

@client.listen()
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$bot_restart'):
        if message.author.guild_permissions.administrator == True:
            os.system('bash /xxxx/discord-bot-restart')
            await message.channel.send('Bot has been restarted')
        else:
            await message.channel.send(f"Permission denied, bad {message.author}!")
    await client.process_command(message)

process_command = Unresolved attribute reference 'process_command' for class 'Bot'

brittle ingot
#

wait what are you using?
discord.Client
or
commands.Bot

sullen shoal
#

Bot

#

for some reason many new comers name the bot instance client. looks like some old crap source is misdirecting them

runic void
runic void
#

i learn python by making this stuff haha

sullen shoal
#

the class is called Bot, so you name it bot

brittle ingot
#

right but does it say:

client = commands.Bot()```
or 
```py
client = discord.Client()
kind wind
#

I have asked a question twice but I haven't fixed the problem. Can you help me?

Problem: I want to make a verify command that gives a role but I fail.

Code:

import discord
import os

client = discord.Client()

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('v!verify'):
    await message.channel.send('You have been verified! Have fun!!!')

client.run(os.getenv('TOKEN'))

Note: I removed the role thing because it gave me errors and kept the text instead.

runic void
kind wind
#

Its a bot problem

slate swan
#

why do some many people use on_message events just use commands

brittle ingot
#

tutorials

sullen shoal
#

old crap sources

kind wind
#

@slate swan because some people may be new

#

and got it from a tutorial

runic void
#

yeah i'm new and like to learn so we use Tutorials

brittle ingot
#

Plus the starter on the docs has always been discord.Client()

brittle ingot
sullen shoal
slate swan
#
import discord
import os
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.presences = True

bot = commands.Bot(command_prefix="v!", case_insensitive=True, intents=intents)

@client.event
async def on_connect():
  print(f'Logged into: {bot.user.name}')

bot.run(os.getenv('TOKEN'))```
sullen shoal
#

and the owner straight up claims this lib isnt beginner friendly. so you gotta have some knowledge of OOP and python classes

brisk helm
#
try:

except:
    print(error)``` How to do soemthging like this?
brittle ingot
#
import discord
from discord.ext import commands
import os

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

@bot.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@bot.command
async def verify(ctx):
    role = ctx.guild.get_role(paste_role_id_here)
    await ctx.author.add_role(role)
    await ctx.reply("Thank you for verifying yourself!", delete_after=45)
    await ctx.message.delete(delay=45)

client.run(os.getenv('TOKEN'))
sullen shoal
kind wind
#

Sorry my discord shut down. What did I lost?

slate swan
#

Doesn't on_ready run multiple tiems @brittle ingot

sullen shoal
#

it does

brisk helm
brittle ingot
#

yes

runic void
#

but why not use client.event and client.command

If somebody is asked "what is website" we can trigger stuff but yeah nvm then ahaha

slate swan
#

yeah transfer him over to on_connect

sullen shoal
brittle ingot
#

on connect runs everytime the bot reconnects to the websocket, which is very frequently.

slate swan
#

ahh

#

i dont use on_ready or on_connect so i didnt remember

brisk helm
brittle ingot
#

on_ready fires once the bot is connected and ready for information if i remember correctly.

slate swan
spice yoke
#

I started using Hikari but the lack of documentation is kind of an issue

sullen shoal
brittle ingot
#

fail

slate swan
#

Can someone help me my server got nuked with channels and roles I was thinking maybe something like which should be as simple as

for channel in await guild.get_channels()
    if channel.name == "name":
        await channel.delete() 

Credit: @silver pumice (he’s helping fix nuke bot make)

silver pumice
#

it's worth noting that the credit to me is not nuking their server

brittle ingot
#

or you can just to ```py
except Exception as e:
raise e

to catch exceptions
sullen shoal
#

try to stay away from except Exception: as much as possible. It is useful at some points but most of the time not.

slate swan
kind wind
sullen shoal
#

never do bare, except: It will catch even BaseException which it shouldn't

brittle ingot
kind wind
#

Another Error

rose hull
proper sluice
#

I'm trying to get the bot to remove reactions from the embed but I can't seem to get the bot's ID to remove the reactions embed = await channel.send(embed = embed) await embed.add_reaction("1️⃣") await embed.add_reaction("2️⃣") await embed.add_reaction("3️⃣") await embed.add_reaction("4️⃣") time.sleep(25) await embed.remove_reaction("1️⃣", client.fetch_user(907341147993702490)) await embed.remove_reaction("2️⃣", client.fetch_user(907341147993702490)) await embed.remove_reaction("3️⃣", client.fetch_user(907341147993702490)) await embed.remove_reaction("4️⃣", client.fetch_user(907341147993702490))

kind wind
#

Error:

Ignoring expectation in command None:
discord.ext.commands.errors.CommandNotFound: Command "verify" is not found```
sullen shoal
#

!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.
sullen shoal
#

not discord.Embed.remove_reaction

kind wind
proper sluice
sullen shoal
#

i see, embed = await channel.send(embed = embed)
please there are almost endless amount of names you can choose from, please name it different

slate swan
runic void
#

now using then commands

@client.command()
async def nft(ctx, arg):
    if arg == "1":
        await ctx.send('arg is 1')
    elif arg == "2":
        await ctx.send('arg is 2')
    else:
        await ctx.send('no arg')

Now with arg it work but ofcourse i receive the error:

discord.ext.commands.errors.MissingRequiredArgument: arg is a required argument that is missing.

any good way to prevent the crash

brittle ingot
kind wind
#

that fixes the problem?

slate swan
#

yeh

sullen shoal
#

you could try?

kind wind
#

I got a whole lot of error

brittle ingot
#

really?

proper sluice
sullen shoal
#

a lot of errors mostly come when you provide invalid token

kind wind
#

That is the error.

sullen shoal
#

from such a basic script

#

its add_roles

brittle ingot
#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
brittle ingot
#

add an s to the end of add_role sorry again 😂

kind wind
#

Was it add_roles instead of add_role?

brittle ingot
#

yes

sullen shoal
#

first being you fetching the User again and again

proper sluice
#

yea the documentation isn't too helpful either

kind wind
#

Again...

sullen shoal
kind wind
#

Something about get_roles

sullen shoal
leaden shoal
#

Hello there!
I'm new in Python and I want to write a discord bot that will show in its status online players from my server.

But when I run the code, the value azura1 is displayed in brackets in the bot status. And I want to display: Playing <players> / <maxPlayers> without brackets.

import requests
import discord
import time
from discord import client
from discord.ext import commands
from config import settings
import os



URL = 'https://skymp-auth.herokuapp.com/api/servers'

resp = requests.get(url=URL)
data = resp.json()

azura = data[0]
print(azura['online'], '/', azura['maxPlayers'])
azura1 = (data[0]['online']),(data[0]['maxPlayers'])

bot = commands.Bot(command_prefix = settings['prefix'])

@bot.event
async def on_ready():
    print('Logged in as')
    print(f'Bot-Name: {bot.user.name}')
    print(f'Bot-ID: {bot.user.id}')
    print(f'Discord Version: {discord.__version__}')
    bot.AppInfo = await bot.application_info()
    print(f'Owner: {bot.AppInfo.owner}')
    print('------')
    bot.startTime = time.time()
    print(f'Start time: {time.gmtime(bot.startTime)}')
    await bot.change_presence(status=discord.Status.dnd, activity=discord.Game("Initializing..."))

    await bot.change_presence(status=discord.Status.online, activity=discord.Game(azura1))

bot.run(settings['token'])

But it would be even better if the bot status displayed: Watching online <online> / <maxPlayers> .
I saw how my friend did it in his code:

    await self.bot.change_presence(status=discord.Status.online,
                                           activity=discord.Activity(type=discord.ActivityType.watching, name=data))
brittle ingot
kind wind
#

oof

brittle ingot
#

it should be get_role(role-id)

kind wind
#

lemme fix that

#

Cut #5?

brittle ingot
#

role-id being the actual ID from the role you getch from the discord server.

sullen shoal
kind wind
#

You know...

sullen shoal
#

httpx, aiohttp are the ones you should go for

kind wind
#

Error No.3

grim oar
#

It's Member.add_roles

brittle ingot
#

you misunderstood me. here i'll redo it so we can get this working for you 😄

kind wind
#

oh-

leaden shoal
grim oar
#

Hmm?

brittle ingot
#
import discord
from discord.ext import commands
import os

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

@bot.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@bot.command()
async def verify(ctx):
    role = ctx.guild.get_role(paste_role_id_here)
    await ctx.author.add_roles(role)
    await ctx.reply("Thank you for verifying yourself!", delete_after=45)
    await ctx.message.delete(delay=45)

bot.run(os.getenv('TOKEN'))
brittle ingot
kind wind
#

lets try this

leaden shoal
brittle ingot
#

it works for some people not for others i've noticed.

grim oar
#

¯\_(ツ)_/¯

kind wind
#

:O

#

IT WORKSSSSS!!!

brittle ingot
#

yay!

#

sorry for the confusion, you can use that command as an example for other commands you produce.

sullen shoal
#

they were trying to change the presence

brittle ingot
#

wth is this?

sullen shoal
#

the code snippet is wrong/bug

sullen shoal
#

yep its archived now, old project

brittle ingot
#

misnaming your bot var is a right of passage 😂

brisk helm
#

whats the permissions to send links on the channel

brittle ingot
#

embed_links im pretty sure

kind wind
#

Can I use the remove_roles to remove the "Not Verified" role?

brittle ingot
#

yes

#

you will need to get the role like we did with the verified role

kind wind
#

Wait a second

sullen shoal
#

its better to provide the role id, so instead of passing the name pass the role id instead

#

if youre passing it the name ofc

brittle ingot
#

that's what we did 😄

#

role id

sullen shoal
#

great

kind wind
#

Oh okay. I just used the "Preview server as role" that is why I got confused but it works perfect

brittle ingot
#

Plus it sets the future for scaling to a DB eventually as most store the role id in their db

brisk helm
#

How to check the channel permissios for some role

sullen shoal
#

also have a look at the examples folder of the repo for more examples then lookup the docs for the stuff you dont understand there

kind wind
#

I now only have to try and make the bot give the "Not Verified" role when someone joins. So I guess I need to use he @bot.event?

sullen shoal
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
brittle ingot
#

for that i would recommend a events handler cog. but yes, you would use an on_member_join event and assign the member that role

brittle ingot
#

!d discord.TextChannel.permissions_for

unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
brittle ingot
#

i believe

sullen shoal
#

hm i gotta go finish my project, afk

brittle ingot
#

ik me too, i've been slacking 😂 this webserver isn't gonna build itself, unfortunately

pale zenith
#

😭 wrong emoji

brisk helm
brittle ingot
#

i mean it might. you aren't assigning it to a variable

brisk helm
#

i dont need to do that

#

lol

slate swan
kind wind
#

So the event should be like:

@bot.event
async def on_member_join():
  notverified = ctx.guild.get_role(role_id)
  await ctx.member.add_roles(notverified)

I am sure I have done something wrong in this code but I made it how I think it is.

brittle ingot
#

yes but slightly different.

#

Add a member parameter in your on_member_join()
then you will need to do member.guild.get_role() instead of ctx.guild since there is no context in an event.

kind wind
#

So...

#
@bot.event
async def on_member_join():
  notverified = member.guild.get_role(role_id)
  await member.guild.add_roles(notverified)
slate swan
#

on_member_join(member)

kind wind
#

Okay

brittle ingot
#

and instead of

await member.guild.add_roles(notverified)

do

await member.add_roles(notverified)
kind wind
#
@bot.event
async def on_member_join(member):
  notverified = member.guild.get_role(role_id)
  await member.add_roles(notverified)
#

this?

brittle ingot
#

looks good to me

kind wind
#

I dont know how to try this

#

I will just put it in and see if there are any errors

brittle ingot
#

start your bot and invite someone to your server.

kind wind
#

Before the commands or after the commands?

slate swan
kind wind
#

I will put this line of code

#

Like below the on_ready function?

slate swan
brittle ingot
#

doesn't really matter honestly, but i would recommend keeping events together and commands together for easier readability

slate swan
#

on_member_join is an event like on_ready and on_message

kind wind
#

Where the arrow points

brittle ingot
#

right, he just wanted to know in which part of the file it should be located

slate swan
kind wind
#

Okay

slate swan
brittle ingot
#

that just means its not being used.

kind wind
#

Can I use the same variable as in the verify command? The role2 is the "Not Verified" role

slate swan
brittle ingot
kind wind
#

okay

#

So I can remove the

notverified = member.guild.get_role(role_id)

Or I need to keep it there?

slate swan
#

When I save a file as a PNG file. And it saves another one with the same name and same directory. Does it override? Or are there 2 files

runic void
#

How do i get the Embed text Star next to Class?


   embed2.add_field(name=':crossed_swords: Power:', value=str(_power), inline=True)
    embed2.add_field(name=":dart: Accuracy:", value=str(_baseAccuracy), inline=True)

    embed2.add_field(name=':military_medal: Class:', value=str(_skill_class), inline=False)
    embed2.add_field(name=":star:  Stars:", value=str(_level), inline=True)
slate swan
#

@runic void

embed2.add_field(name=':military_medal: Class:', value=str(_skill_class), inline=True)
runic void
slate swan
#

?

runic void
slate swan
#

Okay then

#
   embed2.add_field(name=':crossed_swords: Power:', value=str(_power), inline=True)
    embed2.add_field(name=":dart: Accuracy:", value=str(_baseAccuracy), inline=False)

    embed2.add_field(name=':military_medal: Class:', value=str(_skill_class), inline=True)
    embed2.add_field(name=":star:  Stars:", value=str(_level), inline=True)

brittle ingot
#

You may need to add in blank fields to format the embed how you want tbh

runic void
slate swan
#

Nah won't work

brittle ingot
#

An empty field would go between 1st and 2nd then 3rn and 4th. You need to put “\u200b” in the embed fields name and value plus make sure all inline are set to True

slate swan
slate swan
keen magnet
#

Guys why I am getting

requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://discord.com/api/v8/oauth2/token

The code is 100% correct. It was working and it suddendly stopped.

What I tried:

*running this in gitpod workspace,
*making new app in discord dev portal,
*sending user-agent,
*different discord account.
It drops the same error all the time
brisk helm
#

how to check me pythone version

keen magnet
#

python --version

slate swan
#

can someone walk me through how to use waitfor? it's so confusing

brisk helm
runic void
# brittle ingot An empty field would go between 1st and 2nd then 3rn and 4th. You need to put “\...

Thanks ! Fixed it by also filling blanc one ast last so now i have them alligned also better then the screenshot above

The following will also fix the below problem

    embed2.add_field(name=':crossed_swords: Power:', value=str(_power), inline=True)
    embed2.add_field(name=":dart: Accuracy:", value=str(_baseAccuracy), inline=True)
    embed2.add_field(name="\u200b", value="\u200b", inline=True)
    embed2.add_field(name=':military_medal: Class:', value=str(_skill_class), inline=True)
    embed2.add_field(name=":star:  Stars:", value=str(_level), inline=True)
    embed2.add_field(name="\u200b", value="\u200b", inline=True)
brittle ingot
#

I mean if your happy with that 😄

slate swan
#
snipe_message_author = {}
snipe_message_content = {}
snipe_image_content = {}
@bot.event
async def on_message_delete(message):
    snipe_message_author[message.channel.id] = message.author
    snipe_message_content[message.channel.id] = message.content
    snipe_image_content[message.attachments[0].url] = message.attachments

@bot.command(aliases=['s'], name='snipe')
async def snipe(ctx):
    channel = ctx.channel
    em = discord.Embed(color=0x2f3136)
    em.add_field(name=f"Last deleted message in {channel.name}:", value=snipe_message_content[channel.id])
    em.set_footer(text=f"This message was sent by {snipe_message_author[channel.id]}")
    em.set_image(url=f'{message.attachments[channel.id]}')
    await ctx.send(embed=em)``` how can i snipe the image url of a deleted message
runic void
brittle ingot
slate swan
#

really?

#

why and how lol

brittle ingot
#

Yeah :/

#

Because once a message is deleted it’s no longer intended to be accessed or used. And essentially the author has revoked permissions to its contents by deleting it.

slate swan
#

so when bots do things like message logs

#

is that not too against tos?

brittle ingot
#

Therefor you would be accessing info without expressed permissions

brittle ingot
slate swan
#

When I save a file as a PNG file. And it saves another one with the same name and same directory. Does it override? Or are there 2 files

south bane
#
@bot.command(name='spam', help='Spams the input message for x number of times')
@commands.is_owner()
async def spam(ctx, amount:int, *, message):
    limit = 1000
    if amount <= limit:
        for i in range(amount): 
            await ctx.send(message)
    else:
        await ctx.send(f"The spam limit is {limit}")
    await ctx.message.delete()  ```


can somebody tell me how to stop this command by interacting on a button? yes i m in 2.0
(for educational purpose)
brittle ingot
#

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

south bane
#

i was gonna do it xd

shadow wraith
#

meh buttons are kinda broken with py now

#

i dont think interacting with them works anymore

thick sigil
#

why would they not

south bane
#

it works perfect

#

unless ur not using some 3rd party libraries maybe?

sullen shoal
#

oops wrong reply

shadow wraith
#

with discordcomponents do you need to make a @bot.event for a button_click or has the syntax changed?

slate swan
shadow wraith
#

ayo what 💀 really

lament mesa
shadow wraith
slate swan
#

no

shadow wraith
#

oh lol

slate swan
#

U can use 2.0

#

Buttons

#

discord.ui

#

and it works well

shadow wraith
#

can you just show me an example :torl:

sullen shoal
#

although you wont get slash commands so your bot is kinda useless if you dont get message intent after it reaches 75 guilds

slate swan
shadow wraith
slate swan
shadow wraith
#

did they add any updates or am i just being stupid

slate swan
#

u need to install it like this

#

u better join discord.py server for help regarding this if u want!

shadow wraith
#

pip3 momen

#

can you also use pip3

slate swan
#

u use an ide or replit?

shadow wraith
#

ide

slate swan
#

oh

shadow wraith
#

its vsc

slate swan
#

try it

shadow wraith
#

i changed my version to 3.9.5

slate swan
#

u need to add git path

#

to download 2.0

shadow wraith
#

wheres the git path to my life 🥺

slate swan
#

how can u get the name of someones activity? for example "Playing (game)", "watching (whatever theyre watching)"

#

u can just download git from hoogle

shadow wraith
#

oh lmao

slate swan
#

Google

unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

slate swan
#

Uh

#

try master?

slate swan
unkempt canyonBOT
#

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

slate swan
#

This

#

!d discord.Member.activity

unkempt canyonBOT
#

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
slate swan
#

so wouldnt that be something like print(member.discord.Activity.name)?

sullen shoal
#

uh

slate swan
#

or member.activity

#

Yes ig

#

member.activity

#

To get someone's activity

#

u need intents

#

to work

#

yeah that ik

shadow wraith
#

whenever i do brew install git it doesn't work for me 💀

devout iris
#

is this wrong?

#

it shows 1 user only

sullen shoal
#

you need intents

brittle ingot
#

turn on member intents in the developer portal and define intents in your code.

devout iris
#

guild and channel counts are working, only member count is not working

sullen shoal
#

have you defined something related to intents in your code?

slate swan
devout iris
#

nope

sullen shoal
#

there

devout iris
#

how can i make it then

slate swan
#

intents = discord.Intents.all()

sullen shoal
#

pass this to discord.ext.commands.Bot

kind wind
#

How can I check if the ID by the given user (for a bot) is correct?

sullen shoal
#

user id?

#

either use, discord.utils.get or Bot.get_user

devout iris
#

alr i m gonna try

sullen shoal
#

which will be None if invalid

slate swan
#

how can i get what a user is competing in / watching? they dont come up as activity types on the docs

brittle ingot
#

presences

#

or not lol

#

!d discord.Member.activities

unkempt canyonBOT
#

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

brittle ingot
#

@slate swan

slate swan
#

its there?

brittle ingot
#

it returns a list i would recommend printing the list to the console at first so you can see its structure

devout iris
kind wind
# sullen shoal user id?

I want to make like a "submit your bot" command and I want the bot to check if the given id is correct

slate swan
#

so i just print member.activities

devout iris
brittle ingot
unkempt canyonBOT
brittle ingot
#

it should be inside of:

bot = commands.Bot(command_prefix = " ", intents = discord.Intents.all())
sullen shoal
devout iris
#

ah lmao

sullen shoal
#

be sure to put a cooldown on it tho

devout iris
#

alr

kind wind
#

Or it counts as a bot

sullen shoal
brittle ingot
#

back to researching how to create and validate authorization tokens for a webserver ✌️

kind wind
#

If it is none can I make it like "Invalid ID inserted!"

sullen shoal
#

you can do what ever you want

slate swan
kind wind
slate swan
# brittle ingot yes?

it returned this as part of the list <Activity type=<ActivityType.listening: 2>, so would i do something like if member.acticvity.ActivityType.listening?

sullen shoal
#
var = None
if var: ...# its true
if not var: ... # its either False or None
spice yoke
sullen shoal
#

i would not recommend to do if not

#

if var is None

#

or if var is False

slate swan
#

why not just

spice yoke
#

Like I know the methods and classes are well documented, but it’s kinda hard to search what I really need

slate swan
#
if var is None or if var is False:```
slate swan
slate swan
#

(<Activity type=<ActivityType.listening: 2> name='e!help | Emoji.gg ' url=None details=None application_id=None session_id=None emoji=None>,)

sullen shoal
devout iris
slate swan
devout iris
#

like that?

slate swan
brittle ingot
slate swan
#

I prefer using the docs because googling questions with dpy never actually taught me what the methods I was using were doing

slate swan
sullen shoal
# kind wind that is for my command?

if you fetch or get it, it will be either return the object Useror None , you may put a conditional like this,

var: None | discord.User
if var is None:
    ...
else:
   ...```
brittle ingot
#

do you have an on_message event?

devout iris
brittle ingot
#

you will need to use aiohttp to fetch lyrics from somewhere. most likely a database of song lyrics.

slate swan
brittle ingot
slate swan
#

for say

devout iris
#

yep

sage otter
brittle ingot
slate swan
#

indexing

#

right, thats a thing

brittle ingot
#

idk what that sticker is.... werid af

sullen shoal
#

I will tell them to split the artist name and the song name by a comma then,

async def command_name(*, args):
    args = args.strip().split(",")```
brittle ingot
#

i just want to clarify i did not send that. it came from nowhere

slate swan
#

idek what that is

devout iris
brittle ingot
# devout iris

alright add:

await bot.process_commands(message)

inside that event but outside of any if statements

devout iris
brittle ingot
#

nice

devout iris
#

2x on_message

brittle ingot
#

you have two of them?

devout iris
#

nope

#

i did bot.process to 1

#

others havent

#

also sorry for my bad english

brittle ingot
#

you only need one on_message event. just use if statements to check for the different conditions.

rare saddle
#

How to display only the name of the rights that are missing?

The usual output is:

['manage_roles']

Necessary:

manage_roles

devout iris
#

ahh

#

i c

rare saddle
devout iris
#

like that?

#

ah wait

#

lol sorry

brittle ingot
#

if you assign it a variable like permissions you can use list comprehension to resolve it:


permissions = ['manage_roles', 'send_messages']
newList = [permission,replace('_', " ") for permission in permissions]

new list should contain:

newList = ['manage roles', 'send messages'] 

to make it one string use .join() on it:

permsString = newList.join(", ")

which will return:

manage roles, send messages
sullen shoal
#

indentation error

brittle ingot
# devout iris

indentation error because its inside of an if statement. make sure its outside of any if statements.

#

hold on a sec

devout iris
#

alr

brittle ingot
#
@bot.event
async def on_message(message):
    if bot.user.mentioned_in(message):
        await message.channel.send("Hey, ummm...")
    elif message.content == "sa":
        await message.reply("As")
    await bot.process_commands(message)
devout iris
#

ah righttttttt

#

i have to use elif

#

smh

brittle ingot
#

no you don't have to but it keeps code more efficient?. Just notice where the process_commands is indentation wise. its inline with the if/elif not inside of them.

full valley
#

How can I add a timer for a bot command, so if it’s not completed an if statement in the command in a certain time, another bot command happens?

brittle ingot
#

check the time stamp of the command message against the time now and if its over a set amount of time do something other than originally intended.

devout iris
#

yeah alright thanksss

stiff nexus
#
Ignoring exception in view <oping timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label=None emoji=<PartialEmoji animated=False name='🏓' id=None> row=None>:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ui/view.py", line 361, in _scheduled_task
    await interaction.response.defer()
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/interactions.py", line 423, in defer
    await adapter.create_interaction_response(
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/webhook/async_.py", line 189, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

```help the buttons work fine but i get this error why
kind wind
#

Can I ask something? If I put like 2 different files one named "main.py" and the other "commands.py" do I have to copy and paste the bot.run(os.getenv('TOKEN')) or it is already saved and I just put my commands in the commands.py

#

Hello?

sullen shoal
kind wind
#

yeah i tried it

#

I come upon an error which I dont want to fix

#

I will just delete it and continue my work at the main.py

brisk helm
#

How to get The members count in guild

slate swan
#

!d discord.Guild.member_count

unkempt canyonBOT
#

property member_count: int```
Returns the true member count regardless of it being loaded fully or not.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
slate swan
#

I decided to test myself and try to recreate a command from a pre-existing bot, I'd say it turned out well

#

I got a refresher in using the pillow library too lmao

west shuttle
#

Hi. im working with minecraft api but the reply doesnt change even tho my minecraft server is open, any ideas?

slate swan
#

yo can someone help

async def ban(ctx, user: getattr(typing, "Union").__getitem__((getattr(discord, "Member"), getattr(discord, "User",) type(1)))):
    if isinstance(user, type(ctx.author.guild.me.guild.me.guild.me)):
        if getattr(getattr(ctx, "guild"), "roles")[getattr(getattr(user, "top_role"),"position")] > getatttr(user, "t"+"o"+"p"+"_"+"r"+"o"+"l"+"e"):
            getattr(asyncio, ["future","ensure", "_"][1]+["future","ensure", "_"][2]+["future","ensure", "_"][0])(getattr(ctx, "send")("You don't have permissions!".replace("o", "owo").replace("u", "uwu").replace("l", "w").replace("r", "w"))
    if isinstance(user, (getattr(getattr(discord,"member"), "Member"), getattr(getattr(discord, "user"), "User")):
        await getattr(getattr(ctx, "guild"), "ban")(user)
    else:
        await getattr(getattr(ctx, "guild"), "ban")(getattr(discord, "Object")(id = int(str(user)))
getattr(commands, "has_permissions")(ban_members=bool(1))(getattr(bot, "command")()(ban))
#

would be helpful

kindred epoch
magic ore
#

it's a shitpost

slate swan
#

There's no way thats a real ban command

kind wind
#

oof

#

you can use the !eval to see the results of this code

brittle ingot
#

lmao if "top_role" position > "t"+"o"+"p"+"_"+"r"+"o"+"l"+"e" position indeed a shipost

kind wind
#

the output of the code is at #bot-commands

slate swan
#

Ban commands shouldn't be that crazy either

slate swan
#

if isinstance(user, type(ctx.author.guild.me.guild.me.guild.me)):

#

no there's just nothing I can say

#

that's like saying
I've had had had had had had had had had breakfast

#

or
I'm going to be going to be going to be going to the doctor now

slate swan
#

no ideas

west shuttle
#

bruh

slate swan
#

perhaps look somewhere else

west shuttle
#

wdyym

slate swan
#

or give more information so we know where to send you with the issue

#

cuz we work with discord bots here, tho not everything that's in a discord bot, is a problem connected to discord bots

kind wind
#
@bot.command
async def submitbot(ctx):
  await ctx.get_user(id, /)
  await ctx.reply("Your bot has been successfully submitted!",             delete_after=60)

I don't know if this is correct. I just typed it in how I think the command would be

slate swan
#

hm

#

ctx.get_user don't exist

kind wind
#

Bot.get_user

slate swan
#

capital letter?

kind wind
#

!d discord.ext.commands.Bot.get_user

unkempt canyonBOT
slate swan
#

should still not be a capital letter

kind wind
#

I said how I think it would be

slate swan
#

well if you change the wrong things, it will be right

kind wind
#

what are the wrong things

slate swan
#

you passed in id, /

#

you would just pass in the id of a person

kind wind
#

yeah because I want to put the id the message has

slate swan
#

and you would use bot.get_user

slate swan
kind wind
#

Like the person who types the command will have to type the id (of his/her bot)

slate swan
#

oh mhm

#

well pass an argument after ctx

#

typehint it to int

#

maybe an union, but that's just for error handling later

kind wind
#

int what

#

anyways I have to go but I will ask again when I am available for this

slate swan
#

okay

glass fable
#

hey guys, how can i make a random team generator with dsiscord .py? I already have it print all users in a call when called, but how can I get each name and put in random teams of 2 and print the teams

hollow agate
#
if srmod in ctx.author.roles:``` How can I make this work if they have the srmod role or they have a mod role?
slate swan
#

I don't use dpy, but I'm assuming ctx.author.roles returns Role objects

#

so try something like this

lucid verge
#
@client.command()
@commands.has_any_role('Support', 906872608526569482)
async def chart(ctx):
 await ctx.send('**Why do I recieve this when I load up a song?**', file=discord.File('new.png', '*Load up another song > Go into the chart menu > rename the song to your song name > start charting and save!', file=discord.File('video.mp4')))
 await ctx.message.delete()

I get an error?

lucid verge
#

Well i wanna add an image

#

and a video

#

but i get this error

hollow agate
#

Interesting, I'm not sure if you can add an image and a video using a bot, try to add them separately?

slate swan
#

for permmissions it would probably be

lucid verge
#
@client.command()
@commands.has_any_role('Support', 906872608526569482)
async def chart(ctx):
 await ctx.send('**Why do I recieve this when I load up a song?**', file=discord.File('new.png', '*Load up another song > Go into the chart menu > rename the song to your song name > start charting and save!'))
 await ctx.send(file=discord.File('video.mp4'))
 await ctx.message.delete()

is this right?

#

i got this

slate swan
hollow agate
#

I see, thank you!

slate swan
#

Hopefully that works, but I don't use dpy and just checked the docs quickly. Good luck!

devout iris
#
await message.add_reaction(":wastebasket:")
#

error: unknown emoji

hollow agate
slate swan
#

Just use another or statement

hollow agate
#

or role.name == "something"?

slate swan
#
if role.name == "srmod" or role.name == "secondrole" or role.permissions.administrator:
hollow agate
#

I see, thank you so much! <3

slate swan
#

no problemo

#

Although I think it'd be easier just to check the top role perms, no looping that way

#

guild.get_role returns none

#

How to fix this?

#

Either the role you're searching for doesn't exist, or you aren't including the ID in the parameter

#

guild.get_role(role_id)

#

not one of both

#
    async def fetch_mute_role(self, guild: discord.Guild):
        await self.bot.cursor.execute('SELECT roleid FROM mutes WHERE guildid==?', (guild.id,))
        role = await self.bot.cursor.fetchone()
        if role is None:
            role = await self.add_mute_role(guild)
            return role
        role = guild.get_role(role)
        if role is None:
            role = await guild.create_role(name='Muted')
            await self.bot.cursor.execute('UPDATE mutes SET roleid==? WHERE guildid==?', (role.id, guild.id))
            await self.bot.database.commit()
            return role
        return role
#

None of both which is happening

#

guild.get_role returns none, which attends bot to create a role

#

role variable exists

lofty mulch
#

so

#

is cogwatch still viable?

slate swan
devout iris
#

Hey, i want to add reaction to bot's message and when author press the emoji, bot's message gonna delete.

#

How can i make it?

brittle ingot
#

using a wait_for

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
devout iris
#

Okay wait for

#

Well, how can i add reaction to bot's message

peak oyster
#

I wrote a bot that returns a table of information. Often times, the table is more than 4k characters. Can anyone point me a direction of how to split this message into multiple responses please?

await ctx.send(str(ctx.author.mention) + ' Here you go:\n' + tabulate(setups_list, headers="keys", tablefmt="fancygrid"))

devout iris
#

This is adding to my message

#

Don't see return btw*

#

it was await message.add_reaction()

#

But idk how can i add to bot's message

slate swan
#

btw, are commands included in the dpy docs? I'm having trouble finding them?

brittle ingot
# devout iris

assign it to a variable:

message = await ctx.send("Hello World!")
await message.add_reaction('👋')
devout iris
#

But

#

Smh, a sec

#

idk how can i do it for mentioned_in

brittle ingot
#

that adds the reaction to the original message that the user sends not the bots response.

devout iris
#

Yeah this is a problem

brittle ingot
#

so assign it to something else:

msg = await message.channel.send("Hey, ummm...")
await msg.add_reaction("\N{WASTEBASKET}")
devout iris
#

Yeah i'm thinking about this

magic ore
# devout iris

On message only takes one parameter, the message. Not two

devout iris
#

i'm coding for almost 11-12 hours so my brain has dead

#

i have delay :D

devout iris
#

Ah okay i fixed the problem 👍

#

Now i have to add wait_for

rare saddle
#

Even if no error occurs, embed with except discord.HTTPException: is still sent

magic ore
#

Seems like there was an error raised then

rare saddle
sick birch
#

or if you wanna go the LBYL method, you can get the position of both the bot's role and the role that needs to be removed, and compare

rare saddle
sick birch
#

iirc discord.Role has a .potition attribute

whole stream
#

ik this is a stupid error i think but when i use the command i made, it doesnt recognises it/its not working

rare saddle
#

I don't think it's right at all

brittle ingot
#

just check the top role.

#

!d discord.Member.top_role

unkempt canyonBOT
#

property top_role: Role```
Returns the member’s highest role.

This is useful for figuring where a member stands in the role hierarchy chain.
brittle ingot
#
if member.top_role.position > self.bot.top_role.position:
rare saddle
#

maybe self.bot.member.top_role.position

brittle ingot
#

where is this? there may be a way easier way. can you provide the function this is in? is there ctx?

brittle ingot
#

ctx.guild.me.top_role.position

unkempt canyonBOT
#

property me: discord.member.Member```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
rare saddle
brittle ingot
#

That is because its in the for loop. You no longer need that for loop if you are checking top_role

rare saddle
rare saddle
brittle ingot
#

I assume you want to only remove the roles if the person is below the bot's top role correct?

brittle ingot
#

move the for loop inside of that top_role check so if it clears the check the for loop executes.

brittle ingot
#

no. hold on ill type it out so you can see what i mean

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

rare saddle
#

This is how the error output works and the error is duplicated, but another appears

#
if member is None:
            emb1 = discord.Embed(
                description = 'Укажите пользователя которому хотите снять все роли!',
                colour = 0x9370DB
            )
            await ctx.reply(embed = emb1, delete_after = 5)
        else:
                if member.top_role.position > ctx.guild.me.top_role.position:
                    emb2 = discord.Embed(
                        description = 'Я не могу снять все роли, так как моя роль находится ниже.',
                        colour = 0x9370DB
                    )
                    await ctx.reply(embed = emb2)
                else:
                    roles = member.roles
                    for role in roles:
                        await member.remove_roles(role)
                        emb = discord.Embed(
                            description = f'Все роли - {member.mention}, были успешно сняты!',
                            colour = 0x9370DB
                        )
                        await ctx.reply(embed = emb, delete_after = 5)
devout iris
#

it sends ctx message that the bot has rebooted but the bot does not restart

brittle ingot
slate swan
#
sync def kick(ctx, member: discord.Member, *, reason=None):

    await member.kick(reason=reason)

    await ctx.send('User {member} has kicked.') 
#

is there any way i can @ the user who got kicked

brittle ingot
#

member.mention you will need to put it in an f-string

#
await ctx.send(f'User {member.mention} has been kicked.') 
brittle ingot
#

so, when you fetch a members roles it also returns the everyone role.

#

which can't be removed, so you will need to remove that role from the list .

#

!d discord.Guild.default_role

unkempt canyonBOT
brittle ingot
#

whether that fixes the problem i have no clue.

quaint epoch
#

how do i delete messages?

devout iris
#

How can i make a reboot command?

slate swan
devout iris
#

With process manager or smthng

slate swan
quaint epoch
devout iris
slate swan
slate swan
devout iris
slate swan
devout iris
#

Yes

quaint epoch
#

so, what functions can i make that deletes the users message?

slate swan
#

you can't

slate swan
devout iris
#

Can i restart bat file?

slate swan
#

@brittle ingot hm still aint work

slate swan
rare saddle
#

@brittle ingot It's worked, thanks you so much

devout iris
#

Ah

#

A sec @slate swan

#

i have this command

#
os.execv(sys.executable, ["python"] + sys.argv)
slate swan
#

what is this
await print(on_ready)??

devout iris
#

Ah nvm this lol

#

i was trying smthng

slate swan
#

lol 😂

slate swan
devout iris
#

i mean this command was working

#

But it is not working now idk why not working

slate swan
#

any error?

devout iris
#

There is no have error

slate swan
slate swan
# devout iris Smh

put PRINT statements inside each part
for eg.- put print in if and else

devout iris
#

And writing bot has restarted in terminal

brittle ingot
#

Also print(on_ready) may be the issue?

devout iris
#

Hmmm

brittle ingot
#

On ready will print when the bot restarts anyways.

devout iris
#

Bruh

#

Lmao now working

brittle ingot
#

Lol

devout iris
#

Smh

slate swan
#
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='o!')

@bot.command()
async def yur(ctx):
    await ctx.reply('yesirrrr')

@bot.command()

async def kick(ctx, member: discord.Member, *, reason=None):

    await member.kick(reason=reason)

    await ctx.send(f'User {member.mention} has kicked.')

#

anyone know why it aint working?

brittle ingot
#

Maybe you need to enable member intents

slate swan
#

mmm how?

brittle ingot
#
bot = commands.Bot(command_prefix='o!', intents = discord.Intents.all())

You will have to log into the developer portal and enable them on the bot tab of your application as well.

slate swan
#

oh thank you @brittle ingot

devout iris
#

hey i want to make prefix when_mentioned but when i add this event ; this event is working only

#

i.e ;
me : @bot ping
bot: pong
""""""""""""""""
me: @bot
bot: message

#

i want to do it but only second working

brittle ingot
#

you need to change it in your bot constructor.

#
bot = commands.Bot(command_prefix=commands.when_mentioned_or("your-prefix", intents = intents)
devout iris
#

it is already like that

slate swan
#

This is all I have right now

hardy yoke
#

copy paste the code lol

#

or take a screenshot

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
#

It's been on for 6 hours now

#

Idk

#

Wym?

#

Never dealt with that error

#

@slate swan seems like theres no token

#

Did you added your token in the correct place?

#

Im so confused cause of that error

dusk pumice
dusk pumice
lofty mulch
#

What could cause this error?

discord.ext.commands.errors.ExtensionNotFound: Extension '../bot-cogs.dev-panel.py' could not be loaded.

This is my loader:

   if filename.endswith('.py'):
      bot.load_extension(f'../bot-cogs.{filename[:-3]}')
      print ('Arquivos Conexos foram carregados!')```
slate swan
slate swan
dusk pumice
#

It was kinna joke

slate swan
dusk pumice
#

Try this

lofty mulch
#

Is it the print?

dusk pumice
#

😀

#

No

slate swan
#

@slate swan here look

dusk pumice
#

You have to load Just the name of cogs

lofty mulch
#

well shit, still gave the same error

#

line 22, bot.load_extension

dusk pumice
slate swan
#

That's what I use

dusk pumice
#

Yep. I use it too

slate swan
#

Ah

dusk pumice
#

:)

slate swan
lofty mulch
#

It's correct though, it's the exact path

#

going back a folder and going inside another

slate swan
slate swan
#

I'll try

#

Ah

#

Lol it did

dusk pumice
slate swan
#

Ok. I was able to shorten the code

#

But who can help me out with making commands for the bot

#

@boreal ravine question do you have to import discord or you can just do from discord.ext import commands? Sorry for ping btw

slate swan
boreal ravine
#

import commands

slate swan
slate swan
#

In a server

slate swan