#discord-bots

1 messages · Page 358 of 1

little urchin
#

But I want to be able to send this to other people

#

If it's not possible thats ok

upbeat otter
leaden olive
#

why is player still not defined

little urchin
upbeat otter
#

pt

little urchin
#

Ok

#

I will try when I get back to my laptop

upbeat otter
upbeat otter
leaden olive
upbeat otter
#

ok leave it I have no idea don't listen to me

leaden olive
viscid hornet
#

need more info than that

viscid hornet
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

upbeat otter
viscid hornet
leaden olive
viscid hornet
# leaden olive damn

you’re supposed to set the pool to the bot’s pool, not pass it as a separate argument

leaden olive
bright dirge
#

bumping this if anyone has any knowledge with it, also forgot that I'm using disnake not discord.py

slate swan
#
    from urllib.request import Request, urlopen

    req = Request(WEBHOOK_URL, data={'file': open('message.txt','rb')}, headers=headers); urlopen(req)   

TypeError: can't concat str to bytes
#

help anyone

brazen raft
#

You should probably use aiohttp which is included with discord.py and provides an asynchronous interface

slate swan
#

alright

brazen raft
#

If it's a Discord webhook you're trying to send a file thru, you can simply use discord.Webhook.send

quick gust
#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks) and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks). The ones received by the library will automatically be bound using the library’s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url) or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial) classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html):
brazen raft
slate swan
brazen raft
#

Then uh

#

Why are you asking here is my first thing to say

#

My second thing to note is

slate swan
#

..

brazen raft
#

!pypi webhooks

unkempt canyonBOT
bright dirge
brazen raft
ivory falcon
#

is there way to make the variable that i made in the event code change in the commands code? i keep getting "welcoming" is not accessed by pylance in the commands code

#

the event:

async def on_member_join(member):
    welcoming = "off"
    
    channel = client.get_channel(1138787209735045191)
    
    if welcoming == "off":
        print("welcoming is off.")
    elif welcoming == "on":
        await channel.send(f"welcome {member}")```
 
the command: 
 
```@tree.command(
    name="welcome",
    description="Enable welcoming for new user"
)
@app_commands.choices(
    active=[
        app_commands.Choice(name="on", value="on"),
        app_commands.Choice(name="off", value="off")
    ]
) 
async def welcome(interaction: discord.Interaction, active: app_commands.Choice[str], ):
    
    if active.value == "on":
        await interaction.response.send_message("test on")
        print("on")
        welcoming = "on"
    elif active.value == "off":
        await interaction.response.send_message("test off")
        print("off")
        welcoming = "off"```
viscid hornet
viscid hornet
brazen raft
#

Better use a database

#

Unless it's a one guild bot

ivory falcon
slate swan
#

btw can i send json files?

brazen raft
#

Then a bot variable will be the best option

viscid hornet
viscid hornet
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
brazen raft
# slate swan btw can i send json files?

Wdym? Like:

with open("json_file.json", encoding="utf-8") as json_file:
    json_file_for_discord = discord.File(json_file)
    await ctx.send(file=json_file_for_discord)

?

slate swan
#

anyways ill try myself thank you

brazen raft
#

Sure just specify the right headers

slate swan
#

ok

ivory falcon
viscid hornet
brazen raft
slate swan
ivory falcon
viscid hornet
#

damn

brazen raft
# ivory falcon if possible can you explain how to do it 🫠
brazen raft
#

Maybe somebody published a wrapper for it on PyPi already and you're reinventing the wheel

#

Oh you're just sending whatever to a Discord webhook

warped cave
#

@viscid hornet i got my code to work (im from yesterday with the images on a discord bot)

brazen raft
#

Have you checked the website is fine with you scraping their data

warped cave
#

i sill get an error code but it works so xD

viscid hornet
#

i see lots of projects already made

brazen raft
brazen raft
warped cave
# viscid hornet 👍🏽

i get thios error code but it does work

Traceback (most recent call last):
  File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\main.py", line 76, in cypher_ascend_a
    await ctx.send(embed=embed, file=file)
                                   ^^^^
NameError: name 'file' is not defined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\Lib\site-packages\discord\ext\commands\core.py", line 1644, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Luuk\PycharmProjects\discordBot\pythonProject1\.venv\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'file' is not defined```
wary sluice
#

hey is there any way to get amount of transaction, sent by, and time from https//cash.app/payments/90v91cz7nsj6vmfj73g0sknxm/receipt

young dagger
#

Can someone provide an example of how to add a slash command for my Discord bot?

#

I've been using prefix commands the whole time and now I'm trying to get slash commands to work too

young dagger
golden portal
golden portal
velvet temple
#

Anyone got a discord bot with a command like this?

#

I know this isn’t really a place to ask this but it’s so specific idk where else to ask

golden portal
#

discord ID is the epoch time

#

!d discord.Object.created_at

unkempt canyonBOT
golden portal
#

then get the diff between 2 of the snowflake

velvet temple
#

Yeah ik how to make it but I don’t wanna go and make a discord bot just for this rn so I’m just looking for a bot with this command

#

I think pyQuantum has it

golden portal
#

just steal the source

unkempt canyonBOT
#

discord/utils.py line 375

def snowflake_time(id: int, /) -> datetime.datetime:```
golden portal
#

!e ```py
import datetime
DISCORD_EPOCH = 1420070400000
def snowflake(id):
timestamp = ((id >> 22) + DISCORD_EPOCH) / 1000
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)

print(snowflake(1233806632962625667) - snowflake(1233806023458951219))

unkempt canyonBOT
#

@golden portal :white_check_mark: Your 3.12 eval job has completed with return code 0.

0:02:25.317000
velvet temple
#

!e ```py
import datetime
DISCORD_EPOCH = 1420070400000
def snowflake(id):
timestamp = ((id >> 22) + DISCORD_EPOCH) / 1000
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)

print(snowflake(1233804178313445377) - snowflake(1233804180922044457))

unkempt canyonBOT
#

@velvet temple :white_check_mark: Your 3.12 eval job has completed with return code 0.

-1 day, 23:59:59.378000
velvet temple
golden portal
#

backward

velvet temple
#

Oh

#

!e ```py
import datetime
DISCORD_EPOCH = 1420070400000
def snowflake(id):
timestamp = ((id >> 22) + DISCORD_EPOCH) / 1000
return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)

print(snowflake(1233804180922044457) - snowflake(1233804178313445377))

unkempt canyonBOT
#

@velvet temple :white_check_mark: Your 3.12 eval job has completed with return code 0.

0:00:00.622000
golden portal
velvet temple
#

Tysm

golden portal
#

welcome

viscid hornet
#

smth unique and useful

viscid hornet
viscid hornet
#

i thought IDs were different

golden portal
#

tbh it's the easiest way to make IDs

viscid hornet
warped cave
#

This is what i ment, this is what i wanted to make so the code works but i get that error messages when i use the command. But it still sends what i want it to send like in the picture

viscid hornet
warped cave
#

Yes

viscid hornet
#

you could catch it with a try except check

warped cave
viscid hornet
#
try:
    to send the message
except it didnt work:
    so continue```
warped cave
quick gust
#

thats just pseudocode, you need to implement it

upbeat otter
#

invite them to a server where your bot is added

#

like you want to send a message without running a command?

#

,

upbeat otter
#

what is error

#

yes you can dm bot invite links

midnight oracle
#

Okay, I'm gonna try

rain hedge
#
@bot.tree.command(name="ban",description="Bans the user from the server")
async def ban(interaction : discord.Interaction, member : discord.Member, reason : str):
    member.ban
    await member.send(reason)
    await interaction.response.send_message(f"Successfully banned {member} for {reason}", ephemeral=True)

the command does not ban the given user

#

anyone can help

pale zenith
rain hedge
#

I got it to work

#

However

#

if the member cannot be dm'ed how can i make it so the bot says it instead of saying application failed?

midnight oracle
#

It's not an error in the Bot, as I said it worked just fine in the GitHub Codespace and my local machine, so the logs are empty, no error rises

#

The interaction is not taking a second a responder when the error raises, and nope, the defer doesn't worked :/

dusk dagger
dusk dagger
viscid hornet
#

what is it and how do you import it?

dusk dagger
#

It’s an actual Discord command

viscid hornet
#

oh wow, fr?

#

lemme test rq hold on

#

oh there is

rain hedge
unkempt canyonBOT
#
Error handling

A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.

try:
    number = int(user_input)
except ValueError:
    print("failed to convert user_input to a number. setting number to 0.")
    number = 0

You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.

try:
    number = int(user_input)
    item = some_list[number]
except:
    print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")

For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.

vocal snow
#

@rain hedge ^

rain hedge
#

Thanks

midnight oracle
rain hedge
#

Any help you can offer?

vocal snow
#

what have you tried?

rain hedge
#

Im not to familiar with this so bare with me

rain hedge
vocal snow
#

which line is raising the error?

viscid hornet
viscid hornet
#

whats the specific error?

rain hedge
#

i cant get the error since i cleared the terminal

#

accidentally

viscid hornet
rain hedge
midnight oracle
rain hedge
midnight oracle
#

Here's the error

rain hedge
# rain hedge im doing that but everything comes up with a red line under
@bot.tree.command(name="ban",description="Bans the user from the server")
async def ban(interaction : discord.Interaction, member : discord.Member, reason : str):
    await member.ban(reason=reason)
try:
    await member.send(reason)
    await interaction.response.send_message(f"Successfully banned {member} for {reason}", ephemeral=True)
except:
    await interaction.response.send_message("User cannot be messaged", ephmeral=True)
viscid hornet
#

you arent responding quick enough

rain hedge
viscid hornet
#

slash commands raise that error if you dont respond within 3 seconds, like a few others mentioned

rain hedge
#

like remove it from there

viscid hornet
#

the .response. message

rain hedge
#

okay

#

i removed it

midnight oracle
viscid hornet
rain hedge
#

yeah

midnight oracle
#

So, I have to defer all the interactions?

viscid hornet
rain hedge
#

mb

viscid hornet
#

@quick gust i did it

slate swan
#

@viscid hornet dpy: ?tag nabc

viscid hornet
viscid hornet
#

so you dont need to make a new one

rain hedge
#

especially with this try and except stuff

slate swan
#

the exceptions should be documented

viscid hornet
slate swan
#

!d discord.Member.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
viscid hornet
#

lmao bro thinks we're in dpy pointandlaugh

slate swan
#

too used to it 😭

viscid hornet
#

wdym?

slate swan
#

your bot cannot use other bots command/builtins

#

its a builtin command in discord

rain hedge
#

it means discord already has a slash command for a ban built in to every discord server

slate swan
#

the builtin command, no

You would have to implement your own

#

so there comes hierarchy role respect and permissions checks

leaden olive
slate swan
#

I meant implementing your own ban command if thats what you meant

#

since your bot isn't able to use builtin /ban command

slate swan
# leaden olive

Your class Connect4Game doesn't have acquire attribute, except you meant asqlite.Pool.acquire()

slate swan
#

I don't really get it but no, your bot cannot use other bot's command

#

in your own bot, yeah

slate swan
#

or Connection

#

if message from owner? pithink

#

first you should use @bot.command() for this one
then for that command use check @commands.has_guild_permissions()

viscid hornet
viscid hornet
leaden olive
viscid hornet
slate swan
viscid hornet
#

@leaden olive 😭

viscid hornet
leaden olive
unkempt canyonBOT
#
Not gonna happen.

No documentation found for the requested symbol.

slate swan
#

nvm

#

its commands

#

!d discord.ext.commands.has_guild_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions), but operates on guild wide permissions instead of the current channel permissions.

If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage).

New in version 1.3.
viscid hornet
#

im gonna fight you farm_enGRRRR

slate swan
#

🔪

viscid hornet
#

this stinks. how do you get the bots member obj

slate swan
# unkempt canyon

@wide plaza after implementing that check in the logic of the ban command you will also need to provide checks for the role hierarchy like for example

if author's role is above target's role
if bot's role is above target's role

#

if the target is not the author

#

if bot has ban permissions

#

for last one there is also a decorator

#

!d discord.ext.commands.bot_has_guild_permissions

unkempt canyonBOT
#

@discord.ext.commands.bot_has_guild_permissions(**perms)```
Similar to [`has_guild_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_guild_permissions), but checks the bot members guild permissions.

New in version 1.3.
viscid hornet
#

no

#

why do you hate commands?? they're literally miles easier to learn and work with than on_message() listeners

slate swan
#

why would the author ban themselves

#

my bad

#

I meant is the author

quick gust
viscid hornet
#

whis this guy mentioning himself 😭

viscid hornet
#

idk what that is

quick gust
viscid hornet
upbeat otter
#

wdym?

shrewd apex
#

skill issue

upbeat otter
#

ok asher 😭

viscid hornet
#

skill issue

#

both

#

beucase you cant. it literally says commands in the name

shrewd apex
#

just sit and learn python man ;-; give urself a week get familiar with it

viscid hornet
#

yes. py @bot.command() async def caller_message(context): send message

upbeat otter
shrewd apex
#

rip

viscid hornet
upbeat otter
viscid hornet
#

how can you learn python for 5 years and not even know how to make a calculator

upbeat otter
#

wtf 😭did you just say 5

viscid hornet
shrewd apex
#

might wanna take a few duolingo classes while youre at it too ;-;

upbeat otter
viscid hornet
viscid hornet
quick gust
#

!ot 😊

unkempt canyonBOT
viscid hornet
#

i watched all the episodes w my two cousins (one 3y younger and the other 6y younger - both thoroughly component) and it was actually a good watch

viscid hornet
upbeat otter
viscid hornet
quick gust
viscid hornet
#

you do realise we have keyboards right?

#

yes

quick gust
#

if its not one that is implemented in a discord bot, you should probably move to another channel

viscid hornet
#

!paste @iron cosmos

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

viscid hornet
#

code goes there this

#

link goes here

iron cosmos
#

Hello I m slow with my knowledge at the end, the select menu is sent the way I want, but it assigns no roles and the interaction failed, maybe someone can help me^^
https://paste.pythondiscord.com/CI6A

iron cosmos
unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

viscid hornet
#

wheres the error on? what line?

iron cosmos
#

there is no error in the console, the assignment of roles via the selcet menu does not work

viscid hornet
#

since this bot is yours, i dont know how this code would perform, so you'll need to fill me in on this stuff

shrewd apex
#

why are u not using a role select menu?

shrewd apex
#

chosen_roles = [option.value for option in self.values] i am 90% sure this will actually give u an array of role ids

quick gust
shrewd apex
#

member_roles = [discord.utils.get(interaction.guild.roles, id=roles[role]) for role in chosen_roles if role in roles]
so here for role in chosen_roles would iterate over roles ids and if role in roles will just become false since your keys are strings

quick gust
#

Oh nice

viscid hornet
shrewd apex
#

hmm no not able to find any option for specifying roles for role selects there is a channel_type lemme look up the discord docs

shrewd apex
iron cosmos
# viscid hornet since this bot is yours, i dont know how this code would perform, so you'll need...

First, use !uprank MENTION to open a Select menu. If you have the role 1226501882898288641 you will see the Downrank and Uprank roles in the menu. If you have the role 1226174787962011658 you will see Verified and Rank. If you have 1226501882898288641 and 1226174787962011658 you will see all four roles. If you have none of the roles you will see nothing. That works so far. The roles you choose should be given to the person you mentioned. This interaction failed. I think the problem is that the bot doesn't recognize what you select in the selcet menu.

shrewd apex
#

yeah lol role select menu is auto populated by discord

#

no filters or options allowed

quick gust
#

yeah I figured, if they allowed choosing; that'd be cool

shrewd apex
#

kind of weird ig they allow channel types but not id based filtering

iron cosmos
viscid hornet
shrewd apex
#

or an error happened view errors arent explicitly printed out unless u setup proper logging using the on_error handlers

viscid hornet
#

no, thats not what commands are

leaden olive
#

!paste

#

Still trying to fix that cryLaptop

Unhandled exception in internal background task 'checkGames'.
Traceback (most recent call last):
  File "C:\Users\lenov\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop
    await self.coro(*args, **kwargs)
  File "c:\Users\lenov\Desktop\cogs\cogs\gewinnt.py", line 98, in checkGames
    games = await Connect4.getAll(self)
  File "c:\Users\lenov\Desktop\cogs\cogs\gewinnt.py", line 220, in getAll
    async with self.acquire() as conn:
AttributeError: 'Connect4Game' object has no attribute 'acquire'
grand kettle
#

First, if you don’t specify a command name in the arguments, it will use the function name

viscid hornet
grand kettle
#

second, you’re confusing on_message with commands

viscid hornet
#

“self.acquire()” points to a function in the class called “acquire”

viscid hornet
#

idk how you didnt spot that kekw

leaden olive
viscid hornet
#

also you dont have to create a cursor. the connection is automatically also a cursor

#

show me where you create the bot.pool attribute

viscid hornet
#

and if so, you shouldnt be

viscid hornet
ivory falcon
#

i cant create a normal prefix command with @bot.command() i keep getting AttributeError: 'Client' object has no attribute 'command'

intents.message_content = True
 
bot = discord.Client(command_prefix="?", intents=intents, status=discord.Status.idle)
tree = app_commands.CommandTree(bot)```
brazen raft
#

That's because discord.Clients aren't bots and have no concept of commands

#

If you would have used discord.ext.commands.Bot, the error would go away and the bot would actually be initialized with its own command tree

ivory falcon
# brazen raft If you would have used `discord.ext.commands.Bot`, the error would go away and t...

idk if you meant this by that but when i do that i keep getting this error

tree = app_commands.CommandTree(bot)```
 
error: 
 
```Traceback (most recent call last):
  File "C:\Users\Yido\Desktop\Yido_Bot\bot.py", line 22, in <module>
    tree = app_commands.CommandTree(bot)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Yido\AppData\Roaming\Python\Python312\site-packages\discord\app_commands\tree.py", line 132, in __init__
    raise ClientException('This client already has an associated command tree.')
discord.errors.ClientException: This client already has an associated command tree.```
viscid hornet
fringe prairie
#

Because the bot class already has a command tree initialised to it (as the above person said) you don't need to give it another one (it's telling you that). If you ever create a custom command tree class, you can make it use that instead by specifying it with tree_cls= iirc

viscid hornet
#

well this is new

#

what the fuck is the point of Client then 😭🙏🏽

obsidian hill
#

How to dm the sender when message is sent?

brazen raft
brazen raft
obsidian hill
brazen raft
#

In what form do you have the sender's message

#

Or better yet the sender

#

Members aren't IDs, they're objects

obsidian hill
#

trying toasync def on_message(message): if message.content.startswith('$gen'): send dm

brazen raft
#

If this is supposed to be a bot, you can use the bot class and save yourself a big chain of elif statements

#

But anyway message.author.send(…) in this case

viscid hornet
viscid hornet
#

yeah in a nutshell

#

wait how is solstice here 😭

fast osprey
#

Clients are just a barebones implementation of the discord gateway bot API. They take in the events that are published, with the models that discord publishes, and nothing more. Anything beyond that is essentially just random stuff that whatever library person feels is useful (commands.Bot)

obsidian hill
viscid hornet
#

i got washing to do

pale zenith
pale zenith
#

Mfw i'm a bot

viscid hornet
fast osprey
obsidian hill
viscid hornet
#

relatable

obsidian hill
#

So I run my bot on my pc and it works just fine, so I upload it to my vm and run the cmd and get this bs 😭

#
video_url = f"http:/vm ip:5000/video/{random_video}"
await message.author.send('Your video link can be found [here]({video_url})')``` So If I define this....
#

why the FAWK am I getting sent this

obsidian hill
viscid hornet
obsidian hill
#

Im actually so dumb

obsidian hill
viscid hornet
viscid hornet
#

spent, and i shit you not, 6 hours debugging the entire thing (overexaggerating w the 10 by accident)

#

guess what the error was

obsidian hill
#

Alr so now it sent the link but since the video title has spaces its bugging out, how can I replace spaces with like + or smth?

viscid hornet
unkempt canyonBOT
#

str.replace(old, new[, count])```
Return a copy of the string with all occurrences of substring *old* replaced by *new*. If the optional argument *count* is given, only the first *count* occurrences are replaced.
viscid hornet
#

what does the g mean

spice warren
#

I was informed you're helping badly so I'm here to babysit

viscid hornet
#

also hi link Ewave

viscid hornet
viscid hornet
spice warren
#

The bot is open source, there is a help command, there are bot channels, use your initiative

short tinsel
viscid hornet
viscid hornet
#

wait does the g mean generic or general or smth

short tinsel
#

looks like general

viscid hornet
viscid hornet
short tinsel
#

dw

viscid hornet
spice warren
#

Well, you're giving misinformation to the newbies in here, we're here to both educate you and them

wanton current
viscid hornet
timber dragon
viscid hornet
viscid hornet
viscid hornet
#

i dont get where i went wrong

#

wrong recommendation? wrong solution? wrong roadmap? what did i do wrong??

#

??

spice warren
#

I'm trying to read your message history in here to give an outline and advice but man do you send some amount of nonsense or offtopic messages in here, it's absurd just how much offtopic you speak, or the volume of messages for 1 thing lol, gimme a bit to collate this

viscid hornet
#

also do ping me when you wanna talk because im speaking w some other people on different social media

obsidian hill
#

how do I test when a message is sent if its a DM?

timber dragon
#

message.guild will be None in that case

obsidian hill
#

how do I send msg to a specified channel id?

#

channel.send where channel is defined as id?

viscid hornet
viscid hornet
obsidian hill
#

jp

wanton current
sick birch
#

i've used discord.py enough that i can find pretty much anything easily

slate swan
#

One message removed from a suspended account.

turbid condor
slate swan
turbid condor
#

that's the issue then

#

get_channel takes in an int

slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

turbid condor
#

ok then can you use fetch_channel() and see what it gives

channel = await bot.fetch_channel(id)```
slate swan
#

One message removed from a suspended account.

turbid condor
#

!d discord.Client.fetch_channel

unkempt canyonBOT
#

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

Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread) with the specified ID.

Note

This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_channel) instead.

New in version 1.2.

Changed in version 2.0: `channel_id` parameter is now positional-only.
golden portal
#

fetch doesnt give None btw

turbid condor
slate swan
#

One message removed from a suspended account.

turbid condor
#

for using get_channel and similar function the cache needs to be loaded first

turbid condor
#

like it's doing nothing?

slate swan
turbid condor
#

are you trying to send more than 10 embeds at once?

slate swan
#

One message removed from a suspended account.

turbid condor
#

well it seems your price is a dictionary

#

so you need to format it

vapid parcel
slate swan
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

slate swan
turbid condor
slate swan
#

One message removed from a suspended account.

turbid condor
#

using a image manipulation library

#

u can create a collage and then upload it

golden portal
# slate swan One message removed from a suspended account.

you can send different embed with different images, discord will combine them as long as your embed url is set the same, something like this ```py
embed = discord.Embed(title="Some Images", url="https://www.google.com/")
embeds = [
embed.set_image(url="img_one.png"),
embed.copy().set_image(url="img_two.png")
embed.copy().set_image(url="img_three.png")
embed.copy().set_image(url="img_four.png")
]
await channel.send(embeds=embeds)

embed.copy allows you to recreate a new instance with the exact attribute set. Note that it only supports up to 4 images
slate swan
golden portal
#

welcome

viscid hornet
golden portal
#

for local image embed yes

#

i was showing in general on how to do it with external url

viscid hornet
#

ah ok. i see

#

thats pretty handy. i might try that sometime

obsidian hill
#

Anyone know how I can @ mention someone without pinging them??? Ik its possible I just dont know how, I want to like show the @obsidian hill blue thing without actually pinging the user

quick gust
#

no you can't... unless u mention them inside an embed

naive briar
#

Finally, inclusive asker

hushed galleon
#

you can, if you set allowed_mentions= in send() appropriately

#

!d discord.AllowedMentions

unkempt canyonBOT
#

class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)```
A class that represents what mentions are allowed in a message.

This class can be set during [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) initialisation to apply to every message sent. It can also be applied on a per message basis via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for more fine-grained control.
hushed galleon
#

there's also silent=True if you want a red bubble to pop up without any sound/push notification

snow coral
obsidian hill
quick gust
#
Error handling request
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
    messages, upgraded, tail = self._request_parser.feed_data(data)
  File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
  Invalid method encountered:

    b'\x03'
      ^
Error handling request
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
    messages, upgraded, tail = self._request_parser.feed_data(data)
  File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
  Invalid method encountered:

    b'\x16\x03\x01'
      ^
Error handling request
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/aiohttp/web_protocol.py", line 350, in data_received
    messages, upgraded, tail = self._request_parser.feed_data(data)
  File "aiohttp/_http_parser.pyx", line 557, in aiohttp._http_parser.HttpParser.feed_data
aiohttp.http_exceptions.BadStatusLine: 400, message:
  Invalid method encountered:

    b'\x16\x03\x01'```

@hushed galleon yk what could be causing this? ive noticed it ever since I started running a webhook server for topgg
sick birch
quick gust
#

its been happening too much 😔 any way I can suppress the errors without having to mess with the internals?

sick birch
#

you could probably suppress it top level though

quick gust
#

dang

quick gust
sick birch
#

try/except in the route handler essentially

#

unless this error gets raised even before that

quick gust
#

I'm using topggpy so I could try handling that in their route handler

#

I'll try and get back 👍

naive briar
viscid hornet
#

no messages for 1h 30min 😭🙏

shrewd apex
#

at one point discord-bots channel activity was second only to pygen 🐐

viscid hornet
#

im making connect 4 AI on discord. if any of you wanna play it hmu shrug

viscid hornet
#

basically for some reason, im getting a "cant iterate over NoneType" but the list literally exists and the bot knows it

shrewd apex
#

where?

viscid hornet
#

lemme get the line for you rq

#
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ui\view.py", line 430, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\user\OneDrive\Desktop\minigames\connect4 with ai.py", line 20, in callback
    await self.view.play(
  File "c:\Users\user\OneDrive\Desktop\minigames\connect4 with ai.py", line 129, in play
    if winner := self.is_game_over():
                 ^^^^^^^^^^^^^^^^^^^
  File "c:\Users\user\OneDrive\Desktop\minigames\connect4 with ai.py", line 94, in is_game_over
    for x, _ in enumerate(self.board)
                ^^^^^^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not iterable```
#

line 94

shrewd apex
#

my line 94 meanwhile

#

its line 86 for me

viscid hornet
#

its the list comp part

#

rotated_board = [

#
        rotated_board = [
            [
                self.board[-1 - i][x] for i, _ in enumerate(self.board[0])
            ]
            for x, _ in enumerate(self.board)
        ]```
shrewd apex
#

place_counter function returns None

#

and in play function board is re assigned from it

viscid hornet
#

oh

#

thanks asher

glad cradle
shrewd apex
viscid hornet
viscid hornet
leaden olive
leaden olive
viscid hornet
ivory falcon
#

doesnt the slash commands interactions use user?

    user = interaction.user
           ^^^^^^^^^^^^^^^^
AttributeError: 'Command' object has no attribute 'user'```
quick gust
#

show code

ivory falcon
#
    name="data_test",    
) 
async def interaction( ctx ):
    color = "red"
    user = interaction.user
    user_id = user.id
    ref = db.reference(f"/")
    ref.update({
        
        color: {
            
            "color" : str(color)
        
        }
    
    })
    interaction.send(f"worked {user | user_id}")```
quick gust
#

your function name is interaction 💀

viscid hornet
viscid hornet
ivory falcon
viscid hornet
ivory falcon
viscid hornet
#

do you not know how to:

  1. load the extension
  2. make a cog
  3. run commands in a cog
viscid hornet
unkempt canyonBOT
#
Noooooo!!

No documentation found for the requested symbol.

viscid hornet
#

damn

#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
viscid hornet
#

ok that works

viscid hornet
unkempt canyonBOT
#

await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
viscid hornet
#

you want this this

viscid hornet
#

@slate swan smelly

slate swan
#

Hello could someone help please my bot is working correctly however when I or anyone clicks on one of the buttons I get, This interaction failed.

#

View doesn't have an on_button_click method

#

where did you get that from?

slate swan
#

who told you that this method exists or where you found out about it?

slate swan
ivory falcon
# viscid hornet !d discord.ext.commands.Bot.load_extension
    await bot.load_extension(f"cogs.{filename[-3]}")
  File "C:\Users\Yido\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\bot.py", line 1009, in load_extension
    spec = importlib.util.find_spec(name)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib.util>", line 91, in find_spec
ModuleNotFoundError: No module named 'cogs.'```
viscid hornet
ivory falcon
viscid hornet
ivory falcon
viscid hornet
pale zenith
#

filename[-3] is indexing, not slicing.

viscid hornet
#

how'd i not spot that 😭

#

leo always comes in at the best times

#

hes like jesus but italian i think

pale zenith
#

filename[:-3] is what you want. "Grab until the 3rd last character"

ivory falcon
#

the cogs are now loaded i guess but nothing seems to be happening

viscid hornet
#

explain "nothing happening"

ivory falcon
# viscid hornet explain "nothing happening"

isnt the bot supposed to say hello back to me when i say hello or on_ready event its supposed to print "the cog is ready"

    async def on_ready(self):
        print("the cog is ready")

    @commands.command()
    async def hello(self, ctx, *, member: discord.Member = None):
        """Says hello"""
        member = member or ctx.author
        if self._last_member is None or self._last_member.id != member.id:
            await ctx.send(f'Hello {member.name}~')
        else:
            await ctx.send(f'Hello {member.name}... This feels familiar.')
        self._last_member = member
        
async def setup(bot):
    await bot.add_cog(Greetings(bot))```
viscid hornet
#

and i dont see why it doesnt send. are you doing <prefix>hello?

ivory falcon
viscid hornet
ivory falcon
#

it works now

viscid hornet
#

its alr, now you know prettythumbsup

ivory falcon
#

thank you

leaden olive
#

!psate

#

!paste

#

https://paste.pythondiscord.com/BHWQ

Cant fix this error:

Unhandled exception in internal background task 'checkGames'.
Traceback (most recent call last):
  File "C:\Users\lenov\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop
    await self.coro(*args, **kwargs)
  File "c:\Users\lenov\Desktop\cogs\cogs\gewinnt.py", line 98, in checkGames
    games = await Connect4.getAll(self, self.pool)  # Übergebe self als Argument für die Instanz und self.pool als Argument für den pool-Parameter
  File "c:\Users\lenov\Desktop\cogs\cogs\gewinnt.py", line 223, in getAll
    async with pool.acquire() as conn:
AttributeError: 'NoneType' object has no attribute 'acquire'
frank sleet
#

i want to make a bot that when you send the command rickroll with a user it dms this user mp3 of the song, i made another command that adds the bot to a voice channel and plays the song but that already finished, anyone can help me do the dm thing?

`import discord
from discord.ext import commands

intents = discord.Intents.all()
intents.members = True
from discord import FFmpegPCMAudio
import requests
import json

client = commands.Bot(command_prefix='r',intents=intents)

@client.command()
async def rickroll(ctx):`

quick gust
glad cradle
unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
abstract granite
#

How should I make my cogs load in main.py?

viscid hornet
frank sleet
viscid hornet
viscid hornet
abstract granite
frank sleet
abstract granite
leaden olive
viscid hornet
#

either way, where are you defining the pool in your main file

quick gust
quick gust
leaden olive
#

uhm

vapid parcel
#

Can you get who owns a discord bot, by just the bots User id?

slate swan
#

@viscid hornet this command would solve all the problems in the discord.py world :kekw:

shrewd apex
#

just make a smart sync

quick gust
#

that emoji name @vapid parcel 💀

slate swan
#

😔

vapid parcel
#

Now answer this QUESTION!!!

Can you get who owns a discord bot, by just the bots User id?

#

I don't think public can, but I am sure someone can, but I could be wrong shrug

vocal plover
#

afaik no

shrewd apex
#

should be possible

#

hmm

slate swan
#

doubt

vocal plover
#

iirc it used to say when adding it, but now just refers to "the app's developer"

vapid parcel
#

Dammnnnnn

#

L discord

vocal plover
#

and you can only even get to that stage if it's public

vapid parcel
#

Yeah ik, but, discord should make that public

#

because, then you could see who owns certain bots

#

but then it could be used for attacking too

#

so there is a Plus n a Negative to it

shrewd apex
#

i mean it would be listed on stuff like top gg or smn if the owner really wanted to make it public

vocal plover
#

what's the positive? if devs want people to find them they can make that info accessible

vapid parcel
#

Prolly be used more for attacking than anything, I was only asking to find the owner of this bot to see if he would continue the bot, thats why I was asking

vocal plover
#

if they dont then people shouldn't be able to

vapid parcel
#

alr, goodbye ❤️

vocal plover
#

lol are you seriously reacting to messages of people having a discussion with a clown whose emoji name contains a racial slur

quick gust
#

:/

vapid parcel
#

its from a big big server

#

let me think of the name

#

Its from this server

vocal plover
#

for the longest time we weren't allowed reactions in this channel because people abused them, and now idiots like you come in with the apparent intent of getting the permission removed again

vapid parcel
tight obsidian
#

Hello @vapid parcel please don't use emojis with slurs in the name

quick gust
#

bro summoned the mod

vapid parcel
#

idc for the name, i just like the emoji

quick gust
#

get the gif of the emoji, add it to a priv server, with a friendlier name

vocal plover
vapid parcel
vocal plover
#

insinuating people are clowns for having an opinion on privacy is... unhelpful

tight obsidian
#

I have reduced motion on, so it doesn't even animate until I hover on it. The 🤡 is objectively better

vapid parcel
#

i never read the emoji names

quick gust
#

just show me where you're setting the bot pool first

quick gust
vapid parcel
quick gust
#

I'd prefer you share the code (after removing the credential)

vapid parcel
#
class Status(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.loop = asyncio.get_event_loop()
        self.pool = None
        self.update_status_task = self.loop.create_task(self.update_status())

    async def create_pool(self):
        try:
            self.pool = await aiomysql.create_pool(
                host='',
                user='',
                password='',
                db='',
                loop=self.loop)
        except Exception as e:
            print(f"Failed to create pool: {e}")```
#

This is what I use for myself, which works perfectly fine

#

But I have no clue what you are doing, so can't really help 😭

vapid parcel
slate swan
#

One message removed from a suspended account.

leaden olive
golden portal
slate swan
#

since there will be more place for them? I don't really know

slate swan
tacit aspen
#

guys i reset my secret client key and my bot doesnt work anymore

#

how can i fix this

frank sleet
turbid condor
#

to send a local file you will first need to wrap it in discord.File() object and then send it using file parameter of send

#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send)s.
turbid condor
#
# Get the file path
file_path = os.path.join("example.mp3")
# Wrap it in a File Object
file = discord.File(file_path, "Whatever.mp3")

# Now send it
await member.send(file = file) # member is your discord.Member object
ivory falcon
#

is there a reason why "entered" variable keeps returning as none even though something is entered through the form modal

@bot.tree.command(
    name="data_test"    
) 
async def data(interaction: discord.Interaction):
    entered = await interaction.response.send_modal(send_data())
    print(f"{entered}")
    
    color = entered
    user = interaction.user.id
    ref = db.reference(f"/")
    ref.update({
        
        user: {
            
            "color" : str(color)
        
        }
    
    })```
golden portal
# ivory falcon is there a reason why "entered" variable keeps returning as none even though som...

your send_data modal would hold your textinput value, happens after submitting the form, interaction.response.send_modal method doesnt return anything. just move your database logic inside on_submit method of send_data, such as ```py
class SendData(discord.ui.Modal):
color = discord.ui.TextInput(label="Color")
async def on_submit(self, interaction: discord.Interaction):
color_value_set = self.color.value # get color value
# do db logic here

in your slash command, just use them as ```py
await interaction.response.send_modal(SendData())
ivory falcon
golden portal
potent light
#

Is there a way to have more than 5 buttons with Discord.py only? send() and edit() don't seem to have components= and view only handles 5 buttons and there's apparently no way to add two views to a message.

shrewd apex
#

u can have 25 buttons

potent light
shrewd apex
#

just add the buttons how you normally would based on the order u added it the buttons will automatically formatted

#

!d discord.ui.button

unkempt canyonBOT
#

@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
shrewd apex
#

if u want to define which row it will go in use the row property or argument

potent light
shrewd apex
#

works now add all the buttons u want like that

#

and just send the view it should show all the buttons u have added

#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
shrewd apex
#

also takes in a row= similar to how label= u have added

potent light
#

@shrewd apex it worked. The issue was related to not mentioning row=.

#

Thanks man.

shrewd apex
#

👍

#

not defining row shouldn't affect anything but no harm in doing so ig

ivory falcon
#

if its possible can you explain what should i do 😭

quick gust
#

the answer is going to be no

#

what you need to do is copy the entire on_submit function and put it inside your send_data class

#

you'll also need to add self to the parameter and access the "entered" value however discord allows you to

golden portal
#

i already did explain it, the best thing you can do right now is copy the example and see how it works, it's a working example with a solution pointing to what you're trying to do

obsidian hill
#

How do I test / read a users status when it’s updated or just check it every mins

golden portal
#

!d discord.on_presence_update

unkempt canyonBOT
#

discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.

This is called when one or more of the following things change:

• status

• activity

This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences) and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled...
rain hedge
#

How can I make a bot check if a role has been given to somebody?

spice warren
#

You can check if the role is within their roles already:
if Role in Member.roles:

#

!d g discord.Member.roles

unkempt canyonBOT
#

property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
timber dragon
#

Member.get_role(id) is not None works too

slate swan
#

.

cloud dawn
timber dragon
#

yup

#

so will Member.roles

cloud dawn
abstract granite
#

@viscid hornet plis help me with cogs

quick gust
#

just ask

rain hedge
spice warren
#

Well Member here is undefined. I used it as a placeholder for an existing Member object, maybe such as interaction.user in your case

rain hedge
#

I need it to scan for any member in the guild and check if they have staffrole

slate swan
#

If I would try to use bot's get_channel function and it would return None and after that use fetch_channel coro and it would return a channel, would it be added to the cache so it works the next time with get_channel or would I have to store the fetched channel in my own cache?

#

(yes thats alot of woulds)

fast osprey
#

You can't directly insert things into cache. Channels you have permission to should be cached in the first place, so it's probably worth sussing out why that is

viscid hornet
viscid hornet
viscid hornet
snow coral
#

its only that command though

viscid hornet
stuck hearth
#

how do i make slash commands for dms

dusk dagger
stuck hearth
dusk dagger
stuck hearth
dusk dagger
stuck hearth
#

ok thank you

dusk dagger
# stuck hearth ok thank you

You should also understand the concept of what syncing is and when to sync and you can find information about that on the hyperlink in that link

stuck hearth
void mauve
#

Im trying to create a forum post using discord.py library, but it doesnt create any nor it does throw any errors. What might the issue be?

    async def _create_products(self, channel: discord.ForumChannel):
        for product in self.data['products']:
            try:
                print(product)
                product_utils = self.ProductModeUtils(product)

                print(channel, channel.id)
                
                product_thread = await channel.create_thread(
                    name=product['label'], auto_archive_duration=10080,
                    embed=discord.Embed(
                        title=product_utils.title,
                        description=product_utils.description
                    )
                )

            except discord.HTTPException as e:
                print(f"An error occurred: {e}")

p.s. channel object is passed correctly as well as self.data json

fast osprey
#

You're excepting a specific type, is it possible you're getting some other uncaught exception that you aren't logging?

void mauve
fast osprey
#

Are you getting either of those prints?

void mauve
#

all of the data passed is correct

fast osprey
#

Presumably just one of each?

#

or are you getting several

void mauve
#

one of each, like the print statements supposed to do

{'label': 'test-product', 'description': 'This is a long description of test product', 'price': 1500.0, 'curr
ency': 'USD'}
en 1224700856176476161
fast osprey
#

And if you pass in multiple products, do you only get those 2 prints or do you get 2N?

void mauve
#

I just sticked to one item in the list, no point in setting multiple

fast osprey
#

Well if you pass in multiple, that would narrow down if a) it is going through all and discord thinks it's making them or b) you're erroring on trying to make the first one and not seeing the error

burnt iris
#

Hello, which library can I use so I can add buttons and that?

wanton current
#

what library are you using?

fast osprey
#

Pretty much all of the major libraries support them at this point

burnt iris
burnt iris
fast osprey
#

Well that's not a library that exists on pypi at least

#

discord-component is, though it hasn't been updated in over a year so shrug

burnt iris
fast osprey
#

It's a very opinionated question lol

wanton current
burnt iris
burnt iris
wanton current
burnt iris
wanton current
#

there's examples in the discord.py github repository including button examples

vapid parcel
viscid hornet
#

ohhh i see

viscid hornet
#

you seem familiar

#

didnt i already answer your question?

slate swan
#

hey idk if this counts as discord bots but its got to do with insta claiming a ticket #1234248356642029659 and yeah ive made some post about it pls help am stuck 😭

fast osprey
#

It is against discord TOS to write automation that works on user accounts just fyi

swift siren
#
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/bot.py", line 947, in _load_from_module_spec
    await setup(self)
AttributeError: 'Command' object has no attribute 'remove_command'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/jishaku/features/management.py", line 61, in jsk_load
    await discord.utils.maybe_coroutine(method, extension)
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.jail' raised an error: AttributeError: 'Command' object has no attribute 'remove_command'
class jail(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.lock = asyncio.Lock()

    @commands.group(name = "jail", description = "jail command mf" , invoke_without_command = True)
    async def jail(self, ctx): 
        await self.bot.get_cog('events').cmdhelp(ctx, 'jail')


    @commands.command(
        help="view the jailed users in the guild",
        usage="jail users",
        aliases=["arrested"],
        brief = """example: ,jailed"""
    )
    @commands.cooldown(1, 5, commands.BucketType.user)
    @blacklist()
    async def jailed(self, ctx):
     # ect rest of my code

    @jail.command(
        help="view the jail module settings",
        usage="jail settings",
        aliases=["config"],
        brief = """example: ,jail settings"""
    )
    @commands.cooldown(1, 5, commands.BucketType.user)
    @blacklist()
    async def settings(self, ctx):
    # blah blah
swift siren
#

resolved

obsidian hill
#

How can I use on_presence_update to check if presence is equal to something?

#

!d discord.on_presence_update

unkempt canyonBOT
#

discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) updates their presence.

This is called when one or more of the following things change:

• status

• activity

This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences) and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) to be enabled...
upbeat otter
fierce ridge
#
import discord
from discord.ext import commands

intents = discord.Intents.all()
client = commands.Bot(command_prefix="!", intents=intents)

@client.event
async def on_ready():
    print("Bot is Ready!")

@client.command()
async def hello(ctx):
    await ctx.send("Hi")

client.run("uMUvax8SLfhdd1Mwg")
#

this dosent work

turbid condor
# fierce ridge

read the the last 3 lines the literally tell you what you need to do

fierce ridge
#

mb bro

#

@turbid condor yo in 2022 there used to be a website where there is gui for embedded messages then it gives python code or js code for tht

#

u know tht website?

turbid condor
#

nope sry never heard of it or used it

fierce ridge
#

ok

#

found it

fierce ridge
#
yo
can u help me once plz
Image
i wanna make embded like this
embed message
but im lost
can u give the code ?
unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
fierce ridge
#

im kinda lost

#

so the new vouch is title

#

the strts r discription

turbid condor
fierce ridge
#

i got

turbid condor
#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
fierce ridge
#

i got it

#

how to menmtion user

#

and get his pfp?

turbid condor
#

!d discord.Member.mention

unkempt canyonBOT
fierce ridge
#

so like this

#

embed.add_field(name="Vouch:", value=discord.Member.mention, inline=False)

turbid condor
#

!d discord.Member.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
fierce ridge
#

async def vouch(ctx,stars,user,description,member: discord.member):
await ctx.send(member.mention)

#

? this?

fierce ridge
#

oh k

#

pfp?

fierce ridge
turbid condor
#

it's for getting the pfp

fierce ridge
#

ok

#

@turbid condor some error

turbid condor
#

upload em

fierce ridge
#

from strt

#

so basically here is the codse

#
@bot.command()
async def vouch(ctx,stars,user,description):
    
    embed=discord.Embed(title="⭐"*int(stars))
    embed.set_author(name="New Vouch Created", icon_url=discord.Member.display_icon)
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1219365229813567501/1227943364838555688/rk67YOS.png?ex=66302d20&is=662edba0&hm=c833cc8d0ae55a9b068083f8ed7ada1f03e14357dc5ed27df13a8dd9807ef616&')
    embed.add_field(name="Vouch:", value=description, inline=False)
    embed.add_field(name="Vouched By:", value=discord.Member.mention, inline=True)
    embed.add_field(name="Vouched To:", value=user, inline=True)
    embed.set_footer(text="Time")

    await ctx.send(embed = embed)
turbid condor
#

embed.set_author(name="New Vouch Created", icon_url=discord.Member.display_icon)
it's display_avatar not icon

fierce ridge
#

oh

#

@turbid condor

#

same error

turbid condor
#

that's half of the error need full traceback

fierce ridge
#

ill send dm

turbid condor
#

just send it here

fierce ridge
#

itts txt message dosent let me send

turbid condor
#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

turbid condor
#

use this

#

but can you show me what you did

fierce ridge
#

@turbid condor

#

the discord.member.mention

#

dosent work

#

gives this

turbid condor
#

yeah since it need to be a discored.Member object

fierce ridge
#

wt

turbid condor
#

by itself it's nothing just an empty class

fierce ridge
#

i just want to ping the author

#

wts the command for tht

#

ping author

turbid condor
#

ctx.author.mention

fierce ridge
#

@turbid condor

#

ctx dosent work

#
@app_commands.describe(stars = "How Many Stars Do You Give?")
@app_commands.describe(user = "User You Want To Vouch")
@app_commands.describe(message = "Message")
async def say(interaction: discord.Interaction, stars: int, user: discord.Member, message: str):

    embed=discord.Embed(title="⭐"*stars)
    embed.set_author(name="New Vouch Created")
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1219365229813567501/1227943364838555688/rk67YOS.png?ex=66302d20&is=662edba0&hm=c833cc8d0ae55a9b068083f8ed7ada1f03e14357dc5ed27df13a8dd9807ef616&')
    embed.add_field(name="Vouch:", value=message, inline=False)
    embed.add_field(name="Vouched By:", value=discord.Member.mention, inline=True)
    embed.add_field(name="Vouched To:", value=user.mention, inline=True)
    embed.set_footer(text="Time")

    await interaction.response.send_message(embed=embed)
#

where do i put ctx here?

#

im a bot

turbid condor
#

discord.member.mention replace this

fierce ridge
#

replace this

#

with?

turbid condor
fierce ridge
#

ctx

#

gives error

upbeat otter
fierce ridge
#

ctx is not mention

upbeat otter
#

ctx is for text commands

fierce ridge
#

ahh thx

turbid condor
#

wait earlier it was ctx

fierce ridge
#

i changed

fierce ridge
#

u forgot? lol np bro

fierce ridge
#

@turbid condor last help and im leaving

#
@bot.tree.command(name="vouch")
@app_commands.describe(stars = "How Many Stars Do You Give?")
@app_commands.choices(stars = [
    discord.app_commands.Choice(name = '⭐',value= 1),
    discord.app_commands.Choice(name = '⭐⭐',value= 2),
    discord.app_commands.Choice(name = '⭐⭐⭐',value= 3),
    discord.app_commands.Choice(name = '⭐⭐⭐⭐',value= 4),
    discord.app_commands.Choice(name = '⭐⭐⭐⭐⭐',value= 5)
])
@app_commands.describe(user = "User You Want To Vouch")
@app_commands.describe(message = "Message")
async def say(interaction: discord.Interaction, stars: discord.app_commands.choices[int], user: discord.Member, message: str):

    embed=discord.Embed(title=stars.name)
    embed.set_author(name="New Vouch Created")
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1219365229813567501/1227943364838555688/rk67YOS.png?ex=66302d20&is=662edba0&hm=c833cc8d0ae55a9b068083f8ed7ada1f03e14357dc5ed27df13a8dd9807ef616&')
    embed.add_field(name="Vouch:", value=message, inline=False)
    embed.add_field(name="Vouched By:", value=interaction.user.mention, inline=True)
    embed.add_field(name="Vouched To:", value=user.mention, inline=True)
    embed.set_footer(text="Time")

    await interaction.response.send_message(embed=embed)
#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

turbid condor
#

instead of this discord.app_commands.Choice use

#

!d discord.app_commands.choices

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
fierce ridge
#

same

#

@turbid condor

turbid condor
#

open the link in embed and see the examples

fierce ridge
#

@turbid condor spoonfeed me

#

eheee im dum

#
@bot.tree.command(name="vouch")
@app_commands.describe(stars = "How Many Stars Do You Give?")
@app_commands.choices(stars = [
    discord.app_commands.Choice(name = '⭐',value= 1),
    discord.app_commands.Choice(name = '⭐⭐',value= 2),
    discord.app_commands.Choice(name = '⭐⭐⭐',value= 3),
    discord.app_commands.Choice(name = '⭐⭐⭐⭐',value= 4),
    discord.app_commands.Choice(name = '⭐⭐⭐⭐⭐',value= 5)
])
@app_commands.describe(user = "User You Want To Vouch")
@app_commands.describe(message = "Message")
async def say(interaction: discord.Interaction, stars: discordapp_commands.choices[int], user: discord.Member, message: str):

    embed=discord.Embed(title=stars.name)
    embed.set_author(name="New Vouch Created")
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/1219365229813567501/1227943364838555688/rk67YOS.png?ex=66302d20&is=662edba0&hm=c833cc8d0ae55a9b068083f8ed7ada1f03e14357dc5ed27df13a8dd9807ef616&')
    embed.add_field(name="Vouch:", value=message, inline=False)
    embed.add_field(name="Vouched By:", value=interaction.user.mention, inline=True)
    embed.add_field(name="Vouched To:", value=user.mention, inline=True)
    embed.set_footer(text=date.today())

    await interaction.response.send_message(embed=embed)

bot.run("MTIyNzkwMDg2MjExNDgyNDIzMg.GdWaz
fierce ridge
turbid condor
#

i don't see any issue atm

upbeat otter
#

oh nvm that's cut down

turbid condor
#

almost revealed it

upbeat otter
#

Btw how do you get the active developer badge

#

I'm too lazy to search

turbid condor
upbeat otter
fierce ridge
autumn sierra
#

i wanna turn this into slash cmd

#

@commands.command()
@commands.has_permissions(manage_messages=True)
async def clear(self, ctx, count: int):
await ctx.channel.purge(limit=count)

full swift
#

I need help

turbid condor
full swift
# turbid condor rather then saying this state your issue

import discord
from discord.ext import commands
import asyncio
from discord.utils import get
import requests
import itertools
import json
from json import loads
import os
from typing import List
import cv2
from discord.ui import Button , View
import numpy as np
from googletrans import Translator
import datetime
import time
import urllib.request
from skimage import io
from random import randint, randrange , sample, shuffle

how can I install aall that with the lastest version

turbid condor
#

create a file called requirements.txt and put your required libraries in there like ```py
discord.py
requests
cv2
... # and so on

after that in the terminal run ``py -m pip install -U -r requirements.txt``
#

that's the simplest method I can think of

tall delta
#

no

#

not using it is ez

copper flume
#

discord.py

if not entry.target.is_timed_out() and entry.before.is_timed_out():```
entry.before.is_timed_out() doesn't exist so how do I check?
turbid condor
#

what is entry in the first place?

copper flume
pale zenith
#

!d discord.AuditLogEntry.before

#

!d discord.AuditLogDiff

unkempt canyonBOT
#

class discord.AuditLogDiff```
Represents an audit log “change” object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.

Note that accessing an attribute that does not match the specified action will lead to an attribute error.

To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for [`AuditLogAction`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogAction), otherwise check the documentation below for all attributes that are possible.

iter(diff) Returns an iterator over (attribute, value) tuple of this diff.
autumn sierra
#

guys pls help

#

@discord.app_commands.command(name="clear", description="clear messages")
@discord.app_commands.default_permissions(manage_messages=True)
async def clear(self, interaction, amount: int):

    await interaction.response.send_message(f"{amount} messages cleared", ephermeral=True)
copper flume
autumn sierra
#

i am trying to make slash cmd for clear messages
but it doesnt seem to work
anyone care to help pls ?

upbeat otter
autumn sierra
#

bot not responding

#

i got no red flaggd errors too

upbeat otter
#

there must be some traceback in your terminal?

autumn sierra
#

but it just doesnt work
i think some part of the code is wong
but am not able to figure it out

upbeat otter
autumn sierra
#

wht does that mean ?

#

my terminal shows nothing

#

just the path

#

did u check the code ?

#

is there any error in hat?

#

@upbeat otter

upbeat otter
upbeat otter
autumn sierra
#

nop
aftr sorting this issue i was abt to create one

upbeat otter
autumn sierra
#

lol

autumn sierra
#

whr

upbeat otter
#

it should be ephemeral

#

in the send

autumn sierra
#

lemme re run

#

dudeeee
ur the best

#

got it cleared
tysmmmm

#

@upbeat otter

#

gonna work on error handling

upbeat otter
#

also you should defer the response

autumn sierra
upbeat otter
# autumn sierra what does that mean ?

Like after 3 seconds, the interaction times out and if you want to send a message after 3 seconds a slash command is run you won't be able to do that. defering a response beforehand and you can then edit that message

await interaction.response.defer(ephemeral=True)
#super complex processing
await interaction.edit_original_response(content='Cleared messages')```
shrewd apex
#

usually just network latency be like 😔

upbeat otter
#

yeah that too is a major factor

autumn sierra
#

as of now my clear function works fine
so i dont get it
thats y

upbeat otter
# autumn sierra cud u explain the purpose in simpler terms perhaps ?

for example
I run a command that gives me weather information
Now the bot has to fetch the data from another API. Now all this will probably take a lot of time right? Let's say this all takes 5 seconds.

Now the issue with discord Interactions is that whenever you run a slash command. the bot has to return a response within 3 seconds or otherwise this interaction will be lost and there will be no response.

As the weather command took 5 seconds to process, it will never be able to return a response just in time. we use defer to prevent this

autumn sierra
#

how do i implement defer thingy

#

so i use defer thingy for all of my slash ?

#

also aftr i use defer thingy the bot has unlimited time ?

#

to fetch data?

#

@upbeat otter

shrewd apex
#

15 mins

autumn sierra
#

dang

autumn sierra
shrewd apex
#

await interaction.response.defer(ephemeral=True)

autumn sierra
upbeat otter
autumn sierra
#

also i add this after each slash cmd or just once at the end ??

#

@upbeat otter

shrewd apex
#

once at start

pale zenith
autumn sierra
shrewd apex
#

no once at start of each command

copper flume
#

ok

autumn sierra
#

@shrewd apex

#

now i got a red flag error

#

its outside async function

shrewd apex
#

why would it be outside

autumn sierra
#

lol
i think i shud do it in the 2nd last line perhaps ?

shrewd apex
#

u would put it in the first line inside the async function

autumn sierra
#

u told at the start
async doesnt come at the strat

autumn sierra
#

lol
mb

shrewd apex
#

well the statement had await all awaits can only be executed under an async context

shrewd apex
#

no issues