#discord-bots

1 messages · Page 1049 of 1

slate swan
#

!d discord.Client.fetch_webhook

unkempt canyonBOT
#

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

Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") with the specified ID.

Changed in version 2.0: `webhook_id` parameter is now positional-only.
slate swan
#

you can fetch them and use .send()

latent anchor
#

how do i use events and commands at the same time

#

cuz commands doesnt work if there r events

slate swan
#

thats not true, you are doing something wrong

#

change the decorator of your on_message event from .event to .listen()

#

umm guys is ther other new hosting for discord bot py?

latent anchor
#

i tried that
if i use listen then commands doesnt work

slate swan
#

besides heroku?

latent anchor
#

uptime robot with keep alive

slate swan
latent anchor
#

k wait

#

@bot.event
async def on_message(msg):
 embed=discord.Embed(title=">:(", description="Bot angry now", color=0xff0000)
 embed.set_author(name="no u")
 embed.set_footer(text="dont ping bot")
 if '@spice sparrow' in msg.content:
     await msg.channel.send (embed=embed)
#

@slate swan

maiden fable
#

Yea there's the issue

#

Change the event to listen()

#

So it becomes @bot.listen()

latent anchor
#

it will works with that?

latent anchor
#

oh yes tysm

native root
#

so if i do client2 = discord.Client.fetch_webhook(974880363572772874)
client2.send('Hello!')

#

that gives me an error tho

slate swan
#

thats not how object oriented programming works

uncut comet
#

would this work if the emoji isnt in the same servers as my bot?

dusky pine
#

client2 = await discord.Client.fetch_webhook(974880363572772874)
^^^^^^^

await client2.send('Hello!')
^^^^^

slate swan
dusky pine
#

wait really

#

!d discord.Client.fetch_webhook

unkempt canyonBOT
#

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

Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") with the specified ID.

Changed in version 2.0: `webhook_id` parameter is now positional-only.
slate swan
#

they need to use a discord.Client instance, and use fetch_webhook on it, not the class straight

#

"this is a string".upper() is what they should do
str.upper() is what they are doing

uncut comet
# slate swan i dnt think so

ah okay how else can i get the image of a emoji via the id? i tried what i sent above but i couldnt get it to work

dusky pine
#

oh yeah that

uncut comet
#

.

#

but im not sure how read works

slate swan
#

!e discord.Client.fetch_emojo

quaint epoch
#

now that's just sad

slate swan
#

wut,oh

#

!e discord.Client.fetch_emoji

#

im high ig

quaint epoch
#

:sadge:

quaint epoch
uncut comet
#

would this not do the same?

slate swan
#

the heck does that not exist?

quaint epoch
#

!d disnake.Client.fetch_emoji

unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

quaint epoch
#

tf

#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord.
This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
quaint epoch
#

might have to list this as an issue in dev contrib

#

!d discord.Client.get_emoji

unkempt canyonBOT
#

get_emoji(id, /)```
Returns an emoji with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
quaint epoch
#

aha

dusky pine
#

fetch_emoji doesn't exist

uncut comet
#

how can i get the image from the emoji to then create another emoji from it?

quaint epoch
#

im using snekbox in my discord bot, how can i run a docker command to set it up in my procfile in heroku?

#

i wanna run this command, but it says docker can't be found docker run --ipc=none --privileged -d 8060:8060 ghcr.io/python-discord/snekbox

white plume
#

Hi my discord bot broke down suddenly

#

It was running normally before its broke down

#

This is the error please help me check that

#

Thank you!

gaunt ice
#

hm

#

what error is it showing

stiff gorge
#
avatar = member.avatar_url_as(size=1024, format=None, static_format='png')
#

is this correct ?

placid skiff
white plume
slate swan
#

no

white plume
#

Oooops

#

Why I was rate limited

placid skiff
#

You've done something against discord Policies and Agreements

slate swan
white plume
#

Thanks lemme check the policy

dusky pine
regal pulsar
#

!d disnake.Guild.fetch_emoji

unkempt canyonBOT
#

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

Retrieves a custom [`Emoji`](https://docs.disnake.dev/en/latest/api.html#disnake.Emoji "disnake.Emoji") from the guild.

Note

This method is an API call. For general usage, consider iterating over [`emojis`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild.emojis "disnake.Guild.emojis") instead.
regal pulsar
#

lol

white plume
placid skiff
#

So who wants to help me collect most frequently asked questions in this channel? D_D

slate swan
slate swan
# unkempt canyon

weird that they made it a guild method even tho it has nothing do with a server other than its usability

white plume
#

Oh ok thanks

placid skiff
#

common emojis are not even an instance of the Emoji class

#

they're just unicode code

slate swan
placid skiff
#

Yeah but custom emojis are created in guilds

slate swan
#

as i said, "other than usability"

placid skiff
#

why will you even need to retrieve an emoji from an external guild? the bot won't even be able to send it

slate swan
#

they want to get its bytes and upload it to their server

placid skiff
#

to do it the bot needs to be in that guild

pliant gulch
#

I've never seen the endpoint you said

unkempt canyonBOT
#

discord/http.py lines 1344 to 1348

def get_all_custom_emojis(self, guild_id: Snowflake) -> Response[List[emoji.Emoji]]:
    return self.request(Route('GET', '/guilds/{guild_id}/emojis', guild_id=guild_id))

def get_custom_emoji(self, guild_id: Snowflake, emoji_id: Snowflake) -> Response[emoji.Emoji]:
    return self.request(Route('GET', '/guilds/{guild_id}/emojis/{emoji_id}', guild_id=guild_id, emoji_id=emoji_id))```
pliant gulch
#

So obviously it would be a method bound to a Guild instance

slate swan
pliant gulch
#

That's just like any other URL

slate swan
#

i got that wrong because in many libraries its just a client method

native root
#

@slate swan can I add you on discord and message you privately?

slate swan
native root
#

to not spam server chat

pliant gulch
slate swan
#

yeah, true

loud junco
#

Hi sarth

slate swan
#

so they gotta read the emoji using aiohttp

pliant gulch
#

If you want to get the bytes of an emoji, have the emoji CDN url. Make a request, then read the data() of it

slate swan
digital mason
#

Hello I have a question... Is it possible to get a user avatar in current guild and not default avatar

placid skiff
#

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

how to i make like arrest t@g member?

#

and to bot send arrested @stray scarab

placid skiff
#

you will need to pass the member as parameter of your command

slate swan
#

like

#

@bot.command()
async def arrest(ctx)
await.ctx("Arrested memb@er")

#

that?

placid skiff
#

no you have no member paramater in that

slate swan
#

how to do it?

placid skiff
#

you can't develop a bot if you don't know python basics

slate swan
#

-_-

#

this channel is for help

placid skiff
#

help and spoonfeeding are two different things D_D

digital mason
slate swan
#

just help

digital mason
#

Discord functions are coroutines, I dont know the details but they are asynchronous

#

So you have to await when calling, that's why await keyword exists

#

async and await go together, if you add async to a function you have to await

digital mason
#

Does it return the url like avatar_url too or an image object

dense swallow
#

how do i create grps in d.py (slash commands)?

#

!d discord.app_commands.Group

unkempt canyonBOT
#

class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., default_permissions=...)```
A class that implements an application command group.

These are usually inherited rather than created manually.

Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only"), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds "discord.app_commands.guilds"), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions "discord.app_commands.default_permissions")
will apply to the group if used on top of a subclass. For example...
dense swallow
#

like this?

timber kindle
#
async def assignrole(ctx, member: discord.Member, role_id):
  role1 = discord.Role.id(role_id)
  await member.add_roles(member, role1)```

```Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/home/runner/Rolands-Final-Project/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 95, in assignrole
    role1 = discord.Role.id(role_id)
TypeError: 'member_descriptor' object is not callable```

Idk what I'm doing wrong still
jade tartan
digital mason
hushed galleon
hushed galleon
timber kindle
#
 role1 = member.Guild.get_role(role_id)
  await member.add_roles(role1)```

so like this?
hushed galleon
#

the guild attribute of member is lowercase but otherwise thats right

#

hm actually if that assignrole function is a command, you could use the role: discord.Role converter rather than manually getting it

timber kindle
#

oh my god thank you, I've been working on that for 3 days

oak bridge
#

hello. why this for guild in client.guilds:.... for loop can make sure the script could find matching guild.name before printing f'{guild.name}(id: {guild.id})', if I correct understand what he is trying to do?

Thank you

https://realpython.com/how-to-make-a-discord-bot-python/#:~:text=discord.py is a Python,Python's implementation of Async IO.&text=Now that you've installed,your first connection to Discord!

In this step-by-step tutorial, you'll learn how to make a Discord bot in Python and interact with several APIs. You'll learn how to handle events, accept commands, validate and verify input, and all the basics that can help you create useful and exciting automations!

robust fulcrum
#

client_id = ""
client_secret = ""
redirect_uri = ""
code = ""

auth = Auth(client_id, client_secret, redirect_uri, code=code)
api = Api(auth)

Guys i installed a unsplash python api wrapper
There is was written that i need to put the following code
So i have to put client id and secret of my bot or api
It's not written in documentation

hushed galleon
oak bridge
hushed galleon
#

the for-loop variable existing after it's completed is a python feature

robust fulcrum
vale wing
robust fulcrum
oak bridge
#

scope 2 won't change scope 1 if I understand correctly

hushed galleon
#

in python control structures like for-loops dont create new scopes, so whatever you assign in that for-loop will be in the function scope

hushed galleon
oak bridge
#

which units has its scope? context managers? functions?

hushed galleon
oak bridge
hushed galleon
digital mason
#

Ok, I'll update and see if I get any errors

spring flax
#

Is this correct? (the constant is a list)

if any(role in member._roles for role in GLOBAL_CODM_ROLES): 
#

and also would lambda be more suitable for this, or not?

muted dagger
#

@unkempt canyon

#

!eval if any(role in member._roles for role in GLOBAL_CODM_ROLES):

unkempt canyonBOT
#

@muted dagger :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     if any(role in member._roles for role in GLOBAL_CODM_ROLES):
003 |                                                                 ^
004 | IndentationError: expected an indented block after 'if' statement on line 1
muted dagger
#

correct

spring flax
muted dagger
#

i think the indent error might be because of the chat and its nature

slate swan
#

inside a map/filter?

spring flax
#

nope, just for ```py

check member roles

if true: do something

else: else: do nothing

slate swan
#

the if statment with "any" is fine ig, no point of making another lambda

muted dagger
#

sorry, wrong statement

muted dagger
muted dagger
slate swan
#

wtf lmao

#

he was correct

muted dagger
#

its funny watchin a person just going sentimental at sarth and him not even caring.

digital mason
placid skiff
#

Do you have on_message event?

slate swan
#

also, message_content intents

slate swan
digital mason
#

I use intents too, default

#

Could it be the issue

#

Ooh I see

slate swan
placid skiff
#

Ashley tell me some of the dumbest question you've ever read here

slate swan
#

so you will have to explicitly define those

intents = Intents.all()
intents.message_content = True
placid skiff
slate swan
digital mason
#

I got an error, I have to go to developer portal

placid skiff
#

i'm making an extension for the python bot which answer those dumb questions bee_sad

digital mason
#

Because I had already enabled intents before

slate swan
slate swan
placid skiff
#

and i don't think that you're dumb, you're pretty better then most of the people here

slate swan
#

whatever

placid skiff
slate swan
muted dagger
#

simping in chat rn

slate swan
muted dagger
digital mason
#

Just enabled in portal

slate swan
#

wonderful

#

now run the bot

digital mason
#

Lot of stuff changed in 2.0

placid skiff
#

well in the channel where the dumb question is sent
Yeah i know that people would abuse that, i studied automation so i'm used to release product to ignorant people, there will be some advanced checks

digital mason
#

I still get the error, shard id none is requesting..

slate swan
placid skiff
#

don't worry i will be accurate evilfox

slate swan
slate swan
digital mason
#

I'm dumb, I forgot to save changes

slate swan
digital mason
placid skiff
#

over confidence is everything
i would not come that far if i would not be it

digital mason
#

Bot is working, thank you for your time

slate swan
heavy shard
#

is 2.0 released already or is it still in beta?

placid skiff
#

The only truth there is that i'm a busy person D_D

digital mason
#

He surely is, I didnt want to go to so and you know why lol

digital mason
#

Btw I have made an amazing bot if you want to check it out

#

Very funny

placid skiff
digital mason
slate swan
digital mason
#

prefix is pepe

slate swan
#

weird

slate swan
placid skiff
#

Ash is not kindly judge others work "weird"

digital mason
muted dagger
#

yes.

#

frog

slate swan
slate swan
#

id like to check that out

digital mason
#

Yes, there are many commands

muted dagger
digital mason
#

Of course

muted dagger
#

Nice

slate swan
#

😔

#

needs some more calculations

digital mason
#

Someone on discord makes them manually, he sent me the templates and I started the bot from that

muted dagger
digital mason
slate swan
#

you should reduce the text size based on the amount of characters for it to not get out of the "board"

muted dagger
digital mason
placid skiff
slate swan
digital mason
#

😅

#

That code is as messy as a pasta

placid skiff
#

Pasta isn't a mess

placid skiff
#

now i'm offended too

muted dagger
paper sluice
digital mason
#

I did, but the gif makes the sign go up and down

muted dagger
#

hes using a metaphor chucklenuts

muted dagger
digital mason
#

So I had to make changes to x y for each frame

slate swan
#

I need more answers, the whole text doesnt even fit inside the gif

digital mason
#

That wouldnt even show

slate swan
digital mason
#

If you upload it as an emoji

muted dagger
slate swan
#

still, why would it care about your device?

#

@digital mason just a suggestion, in your pepecry command, it deleted the user message and doesnt respond when no text is provided, you can send a "please provide some text" message or something so the user doesn't stays confused what happened

digital mason
#

All the commands call the same function

#

Depending on which mood, so I'll have to make some changes

dull terrace
#

anyone else just sit and stare at print outs while people use their bot like eyesintensify

slate swan
#

do you mean errors by "print outs" ? or some kind of command loggings

dull terrace
#

yeah just logging the state of the game at each interaction, much easier to trace back solutions any bugs that might happen

digital mason
#

Is it possible to hide a command from help

slate swan
#

!rule 7

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

sick birch
slate swan
#

but still

sick birch
#

Yes, but the question itself is not

slate swan
#

^

sick birch
#

I suggest open up a help channel, that way you can get more personalized support

minor oriole
#

how do we save tokens in env files again?

#

token = jkkkdkd

#

like this?

robust fulcrum
#
@client.command()
async def image(ctx,image):
        image = requests.get(f'https://source.unsplash.com/720x600/?{image}') 
        await ctx.send(image)

Guys my command is not working
Can anyone help me?

dull terrace
slate swan
sick birch
robust fulcrum
#
@client.command()
async def image(ctx,image):
        image = requests.get(f'https://source.unsplash.com/720x600/?{image}') 
        await ctx.send(image)

Guys my command is not working
Can anyone help me?

slate swan
#

I did

sick birch
#

If they play the game, they accept to that data being collected

dull terrace
#

i emailed discord about data collection a while back to clarify for my first bot and got a form response

slate swan
sick birch
#

Cool, do what they said then and generally just be respectful of others data

robust fulcrum
dull terrace
dull terrace
robust fulcrum
sick birch
robust fulcrum
sick birch
#

Either that or they’re not collecting data

slate swan
#

....uh

paper sluice
robust fulcrum
#

Hmmm ok

dull terrace
sick birch
#

Not sure about that

dull terrace
#

in the developer portal for each bot rn, heard from others that you're required to fill it at some point

sick birch
#

Ah yeah

dull terrace
#

either way sounds like a good idea

sick birch
#

Does your bot have a dashboard?

#

If so I’d create a page there for terms of service and link it

slate swan
#

i just use my bot's github wiki page

sick birch
#

That’s probably what I’m gonna do if I decide to go commercial with my bot

dull terrace
#

dashboard?

#

I've had a website on to do list for a while now

sick birch
robust fulcrum
#

Guys how to fix this

sick birch
slate swan
#

you are using 2.0, intents kwarg is required

robust fulcrum
slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

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

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

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

robust fulcrum
#

Ok

sage otter
#

How do people actually code on their phones. That gots to be so painful.

digital mason
slate swan
#

similar but you don't need the .members if you don't need it

dull terrace
#

tempted to build it all in python froggy_chill

dull terrace
#

people get so mad if you say you'll do the front end in python doge_kek

slate swan
#

pyscript~

heavy shard
#

is message_content in default intents? he probably gonna need it too

sick birch
#

A dashboard is not very static, so you’re gonna need a JavaScript framework

slate swan
dull terrace
#

😤 gonna have to learn it properly aren't i

digital mason
dull terrace
#

i have a phobia of curly brackets

robust fulcrum
#

I am getting this error now

sick birch
#

Gotta get used to it

digital mason
sick birch
digital mason
#

But how

#

arg is str

#

Wait I think I have already made checks

#

Dammit I hate if elses sus

heavy shard
#

shakes his fist at python's keywords

slate swan
#

!pip regex

unkempt canyonBOT
robust fulcrum
#
@client.command
async def image(ctx,image):
        await ctx.send(f'https://source.unsplash.com/720x600/?{image}')

My command not working

slate swan
#

wait

slate swan
#

what the heck is that command

robust fulcrum
digital mason
#

I have functions that match channels, user mentions

heavy shard
#

he probably needs message_content intent now

slate swan
slate swan
robust fulcrum
#

Hmm

digital mason
nimble plume
#

no

#

no need

#

works without it

digital mason
#

Another thing to learn

#

Does it work with all decorators

nimble plume
#

dont trust me

digital mason
#

Hi lieing Im Vanni

slate swan
digital mason
#

Parentheses

#

I'm confused

nimble plume
slate swan
slate swan
slate swan
digital mason
#

Someone said it before

nimble plume
placid skiff
paper sluice
nimble plume
#

no

slate swan
nimble plume
paper sluice
#

-_-

slate swan
#

lmao

robust fulcrum
#

Btw can we use code of @unkempt canyon in our bot?

slate swan
#

its a callable🤙

nimble plume
sick birch
slate swan
robust fulcrum
nimble plume
slate swan
nimble plume
#

clicked

#

doesnt work

sick birch
nimble plume
robust fulcrum
nimble plume
slate swan
#

i should learn about containers and envs

sick birch
#

Popular DevOps tool

robust fulcrum
#

Ok

nimble plume
robust fulcrum
#

I just need to fill env?

sick birch
#

And run docker compose yeah

nimble plume
#

doctor?

sick birch
#

At least I think it’s docker compose

slate swan
#

Robin is a doctor yes

nimble plume
#

wow

sick birch
#

I have a doctorate in discord bots

nimble plume
#

Dr robin

slate swan
#

see

heavy shard
#

"trust me, I'm a doctor"

slate swan
#

Dr. Robin

nimble plume
#

and you nurse?

slate swan
#

yup

nimble plume
#

MIss. okimii

sick birch
#

Nah he’s a desk clerk

nimble plume
slate swan
#

😔

#

Hunter is a nurse

nimble plume
slate swan
#

he just needs the doctorate

#

aka the helper role

nimble plume
#

decorator?

#

@Hunter()

slate swan
maiden fable
paper sluice
#

@nova summit decorator

nimble plume
#

ok setattr

paper sluice
#

tf, didnt mean to ping

maiden fable
#

Uh

slate swan
nimble plume
maiden fable
paper sluice
#

it didnt ping in the preview anyways, moving on

nimble plume
#

hi

#

My name is Hunter

slate swan
#

🤔

maiden fable
#

Cool

nimble plume
#

hi im okimii

mellow barn
#

Hello, why all parameters are marked optional, when one of them is required?

    пользователь = Option(
      name = Localized(
        "пользователь",
        data = {
          Locale.en_US: "user",
          Locale.ru: "пользователь",
          Locale.pl: "użytkownik"
        }
      ),
      type = Member | User | int,
      description = Localized(
        "рецидивист",
        data = {
          Locale.en_US: "user to ban",
          Locale.ru: "рецидивист",
          Locale.pl: "przestępca"
        }
      ),
      required = True
    ),
    время = Option(
      name = Localized(
        "время",
        data = {
          Locale.en_US: "time",
          Locale.ru: "время",
          Locale.pl: "czas"
        }
      ),
      type = str,
      description = Localized(
        "время бана",
        data = {
          Locale.en_US: "time of ban",
          Locale.ru: "время бана",
          Locale.pl: "czas banu"
        }
      ),
      required = False
    ),
    причина = Option(
      name = Localized(
        "причина",
        data = {
          Locale.en_US: "reason",
          Locale.ru: "причина",
          Locale.pl: "przyczyna"
        }
      ),
      type = str,
      description = Localized(
        "причина бана",
        data = {
          Locale.en_US: "reason of ban",
          Locale.ru: "причина бана",
          Locale.pl: "przyczyna banu"
        }
      ),
      required = False
    )
slate swan
heavy shard
#

я <-- this letter is pronounced "ya"

robust fulcrum
#

@sick birch me not understanding docker can you pls tell

nimble plume
#

i dont know french

nimble plume
robust fulcrum
slate swan
#

all yours robinlemon_smirk

mellow barn
nimble plume
#

stop spamming lemons

sick birch
mellow barn
#

All parameters are getting marked optional, but one of them has required = True

nimble plume
robust fulcrum
nimble plume
mellow barn
nimble plume
#

!e
Print(hi i hate everything/n * 100 +10 lambda x ; [1=1 s1])

unkempt canyonBOT
#

@nimble plume :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     Print(hi i hate everything/n * 100 +10 lambda x ; [1=1 s1])
003 |           ^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
nimble plume
#

yes i forgot a comma

paper sluice
sick birch
nimble plume
robust fulcrum
nimble plume
#

u will not understand

robust fulcrum
#

@sick birch I'll send you my repl invite link will you help me there?

#

I'll not take much time

heavy shard
#

!e
print("A man, a plan, a canal - Panama"[::-1])

unkempt canyonBOT
#

@heavy shard :white_check_mark: Your eval job has completed with return code 0.

amanaP - lanac a ,nalp a ,nam A
mellow barn
# mellow barn

Double checked it, everything is correct, but that parameter is getting marked optional for some reason

stone beacon
#

🗿

jade tartan
#

role = discord.utils.get(guild.roles, name="Muted")
is this correct to add a role to the member?

sage otter
#

No, that’s how you get a role tho.

slate swan
#

shouldnt use utils

sage otter
#

Id use utils if I don’t have a role id

slate swan
#

i would only use it only in your case but if you do have the id you should use Guild.get_role

#

since in its base it would be O(1) but can be O(n) which utils always iterates through all of the roles it will always be O(n) while Guild.get_role uses dict.get()

mellow barn
# mellow barn

Now it's really annoying, all parameters on all slash commands are getting marked optional

sick birch
#

since it supports nested attribute lookup

mellow barn
terse coyote
slate swan
sick birch
#

O(n) is best case, worst case is indeterminate

slate swan
#

mhm

stray mural
#

is there any way to run an infinite while loop thats updating a certain embed completely parrallel to a bot?

mellow barn
# mellow barn Can someone help me?
пользователь = Option(
  name = Localized(
    "пользователь",
    data = {
      Locale.en_US: "user",
      Locale.ru: "пользователь",
      Locale.pl: "użytkownik"
    }
  ),
  type = Member | User | int,
  description = Localized(
    "рецидивист",
    data = {
      Locale.en_US: "user to ban",
      Locale.ru: "рецидивист",
      Locale.pl: "przestępca"
    }
  ),
  required = True
),
время = Option(
  name = Localized(
    "время",
    data = {
      Locale.en_US: "time",
      Locale.ru: "время",
      Locale.pl: "czas"
    }
  ),
  type = str,
  description = Localized(
    "время бана",
    data = {
      Locale.en_US: "time of ban",
      Locale.ru: "время бана",
      Locale.pl: "czas banu"
    }
  ),
  required = False
),
причина = Option(
  name = Localized(
    "причина",
    data = {
      Locale.en_US: "reason",
      Locale.ru: "причина",
      Locale.pl: "przyczyna"
    }
  ),
  type = str,
  description = Localized(
    "причина бана",
    data = {
      Locale.en_US: "reason of ban",
      Locale.ru: "причина бана",
      Locale.pl: "przyczyna banu"
    }
  ),
  required = False
)
sick birch
stray mural
#

ok

slate swan
#

gosh i love saying that word

slate swan
#

youre welcome

minor oriole
#

Can someone guide me in making a discord bot with discord.py?

#

im actually new to the library

#

also not much experience in following docs

sick birch
#

We can help with specific œuestions or errors

minor oriole
#

well sure

slate swan
sick birch
#

what is that letter and how did i make it

heavy shard
#

œ œ œ

slate swan
#

ctrl+c

sick birch
#

œ ah option + q makes that letter

winged bone
slate swan
winged bone
#

?

slate swan
#

he can just switch?

#

and its probably all the same?

winged bone
#

Not quite, especially the slash / app commands are implemented differently

slate swan
#

just check examples on main lol

sick birch
#

good to know that my examples at least help people

minor oriole
#

well the guy here is teaching with nextcord

#

i guess that works too

sick birch
#

The concepts are the same, just apply them to discord.py

slate swan
sick birch
#

In programming the concepts are more important than any library or language, since most of the time they all use the same base concepts, but just reskinned

sick birch
oak bridge
#

@client.event decorator

this question is about the implementation of decorator.

why we can use this decorator in such way to override event handlers in a Client class definition?

the definition of @client.event:
https://github.com/Rapptz/discord.py/blob/master/discord/client.py#L1104

some example implementation of it:

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

    if message.content.startswith('$alert'):
        await message.channel.send('https://www.tradingview.com/pine-script-reference/v5/#fun_alert')

    if message.content.startswith('$ta.wad'):
        await message.channel.send("https://www.tradingview.com/pine-script-reference/v5/#var_ta{dot}wad")
unkempt canyonBOT
#

discord/client.py line 1104

def event(self, coro: Coro, /) -> Coro:```
sick birch
#

I should make more ducky_devil

slate swan
#

😡

spark cloud
#

Is it possible to make money by creating a discord bot?

slate swan
sick birch
#

Sure

sick birch
spark cloud
#

how

#

go to dm

#

@sick birch

sick birch
#

Working as an individual contractor to make bots for people, donations for your bot, paid content, etc

nimble plume
jade tartan
#

Is this right?

placid skiff
sick birch
#

One look at the error logs would indicate the answer to that question

placid skiff
#

The IDE is literally saying "I wanna punch you. I wanna punch you but i can't"

slate swan
#

😭

vocal plover
vocal plover
#

huh I thought I edited that forever ago lol

#

seemingly not

slate swan
#

it was edited yes, but the link wasnt changed

minor oriole
#

do u guys ever get confused between what to use? discord.py pycord nextcord

slate swan
#

not really it really depends on what fork you like the most!

minor oriole
slate swan
#

i mostly like disnake because of their implementation lol

sick birch
#

Don't like any of their implementations

#

I feel like registration of application commands should be decoupled from application command handlers (your actual code)

placid skiff
#

honestly disnake has implemented very well application commands

#

the only thing that is missing is a deco for both application and user commands but tbh is not really necessary

stone beacon
#

Tbh all of them feel the same to me

vocal plover
placid skiff
sick birch
#

That's a step in the right direction

vocal plover
#

I think if beginners had to register their commands themselves it would discourage people from using it entirely

placid skiff
#

disnake is absolutely more user friendly

vocal plover
#

That's a hella lot of friction to make a bot

sick birch
#

They had to weigh beginner friendliness with practicality - that's a difficult one

vocal plover
#

We do at some point want to make it not sync by default, we just need to convince ourselves the fallout is worth it lol

stone beacon
#

It probably is but that's like asking which js framework is better when you have experience with 2 or 3. Some are gonna have some nice quirks or handling but ultimately not that complicated to learn if you know one or two

#

just for me that is

vocal plover
#

wHy mY cOmMaNdS nO wOrK aNyMoRe

sick birch
#

PTSD from when message intents were introduced

stone beacon
#

^

#

This chat was on fire

vocal plover
#

mmmm that was fun

stone beacon
#

The era of no traceback but bot no work

dull terrace
#

anyone have a boilerplate TOS for a bot?

flint isle
#

how do I create a command to log off the bot?

#

so i can limit multiple instances when i forget and am coding on the go

slate swan
unkempt canyonBOT
#

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

Closes the connection to Discord.
flint isle
#

and im using disnake

sage otter
#

did you literally just write
await close() and expect it to work

flint isle
sage otter
#

yea.

#

With parenthesis at the end.

flint isle
#

ok lol I feel so dumb rn

#

How do I check if the person running the command is the bots owner

slate swan
#

!d discord.ext.commands.is_owner , its a check decorator , same for forks too

unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the
owner of the bot.

This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").

This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived
from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
flint isle
#

Is it different for disnake?

wicked atlas
#

!d disnake.ext.commands.is_owner

unkempt canyonBOT
#

@disnake.ext.commands.is_owner()```
A [`check()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.check "disnake.ext.commands.check") that checks if the person invoking this command is the
owner of the bot.

This is powered by [`Bot.is_owner()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.is_owner "disnake.ext.commands.Bot.is_owner").

This check raises a special exception, [`NotOwner`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NotOwner "disnake.ext.commands.NotOwner") that is derived
from [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure").
slate swan
flint isle
#

oh lol i ddnt see that apparenty

slate swan
slate swan
vale wing
#

Those are syntax errors

slate swan
#

I got over a 1000 errors on a 150 line code because of it

slate swan
heady sluice
#

that's a lot

slate swan
#

And it worked fine when disabled

slate swan
vale wing
slate swan
#

Disabling it is the best way

flint isle
#

whats the error handeling?

vale wing
#

I am saying these are not issues by pylint, they're by pylance if you take the closer look

vale wing
#

And those are syntax errors caused by space + tabs in code

slate swan
#

I get mixed up

vale wing
slate swan
slate swan
#

I accidentally turned it on

wicked atlas
#

I mean, those are actual syntax errors

vale wing
slate swan
#

It made me delete vscode

vale wing
#

Said several times

slate swan
flint isle
#

whats the code in the documentation for errors

vale wing
#

Wut

#

I forgot the event or smth

wicked atlas
#

Nope not that one

vale wing
#

on_error is more low level

slate swan
#

I think

#

Or smthinf like that

vale wing
#

No

slate swan
#

Quick question what's the difference between client.commsnd and bot.command?

vale wing
#

Can you not provide misinformation please

slate swan
#

Or is it preferance?

vale wing
wicked atlas
vale wing
#

Names mean nothing to computer

flint isle
#

wait is it "pcr" thats a command

@pcr.error
    async def pcr_error(self, ctx, error):
        if isinstance(error, commands.MissingRequiredArgument):
         
vale wing
#

Oh god why not use global handlers

#

Screw local handlers

#

!d discord.ext.commands.Bot.on_command_error listen to this event

unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be
overridden to have a different implementation...
flint isle
# unkempt canyon

uhhh does this go in a command ?like:

@commands.commands(name="e")
async def e(self, ctx)
    await ctx.send("e a sports")
    await on_command_error(context,exception)
vale wing
#

#BeDRY

vale wing
#
@commands.Cog.listener()
async def on_command_error(ctx: commands.Context, error: discord.CommandError):
    if isinstance(error, commands.MissingRequiredArgument):
        ...
    elif isintance(error, commands.BadArgument):
        ...
    ...
    else:
        raise error```
Very basic error handler
quaint epoch
#
@bot.event
async def on_command_error(ctx, error):
  try:
    await ctx.send(error)
  except BaseException:
    print('Error has occurred in error handler! All hope is lost! You may panic!') # hope this code never executes```
#

it legit happened to me once, an error in the handler

vale wing
#

BaseException 😳

quaint epoch
unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

sus.py:69: Warning: yes
flint isle
#

Attribute commanderror

slate swan
#

what

#

!d disnake.ext.commands.CommandError

unkempt canyonBOT
#

exception disnake.ext.commands.CommandError(message=None, *args)```
The base exception type for all command related errors.

This inherits from [`disnake.DiscordException`](https://docs.disnake.dev/en/latest/api.html#disnake.DiscordException "disnake.DiscordException").

This exception and exceptions inherited from it are handled
in a special way as they are caught and passed into a special event
from [`Bot`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot "disnake.ext.commands.Bot"), [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error").
slate swan
quaint epoch
#

!d disnake.ext.commands.Command

unkempt canyonBOT
#

class disnake.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the
decorator or functional interface.
quaint epoch
#

hm

pure crypt
#

hey guys can someone explain me how i can safe id’s in a json datei with a command? And i need to check if a member’s id who sends the bot a dm is in the datei

slate swan
#

Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "whitelist" is not found

why tf is this happening although its literally a command

#

is it @bot.commands or @bot.command

#
@bot.command
async def whitelist(ctx):
#

bot.command()

#

fr?

#

yea

stiff gorge
#

how to get the sent message time

slate swan
#

!d discord.Message.created_at

unkempt canyonBOT
quaint forum
#

Does ctx.author.mention not work in embeds?

frozen patio
#

It does

slate swan
quaint forum
#

It just does this... instead of actually pinging
< @317342921739206656> (without the space)

frozen patio
#

You need to put them in formatted strings

quaint forum
#

Yeah I tried that as well

frozen patio
#

Ok, is the member in the server?

quaint forum
#

Yeah I'm testing it on myself

frozen patio
#

uhhh

#

You need the braces on the outside

slate swan
#

note that that won't happen in author, title, field names and footer.

sick birch
quaint forum
#

Its in a field one

sick birch
#

Don’t think it works in field titles

slate swan
#

Wont work for the "name", but will for "value"

quaint forum
#

Okay thanks

sick birch
#

Yeah

frozen patio
#

👀

stiff gorge
#
embed.set_footer(text=("Created on  {})".format(ctx.message.created_at.strftime("%d %b %Y %H:%M" ))))

which timezone is this set to ?

slate swan
#

UTC

#

!d discord.Message.created_at

unkempt canyonBOT
slate swan
#

The message's creation time in UTC.

stiff gorge
#

ohk ty

slate swan
quaint forum
quaint epoch
quaint forum
#

oh yeah I know

slate swan
#

you're kinda late HRL

quaint epoch
limber pollen
#

Hello. Can anyone send me official discord.py server

#

Pls ping Me or send me in dms

limber pollen
#

Can anyone please send me some coding related server in my dms

limber pollen
uncut comet
#

has anyone coded a ai chat bot for discord if so what ai did they use? and was it any good?

gaunt mortar
#

I'm wondering why am I getting a "discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: The specified component type is invalid in this context" while trying to add a TextInput to a view...?
Am I missing something about how to use TextInput like adding them to a form or so ?

    async def callback(self, interaction : Interaction):
        embed = discord.Embed(color=0x39fe16)
        embed.add_field(name="Créer un pari", value="Renseigner les champs ci-dessous", inline=False)
        view = View()
        view.add_item(TextInput(label="Test"))
        await interaction.user.send(embed=embed, view=view)
        await interaction.response.defer()
worldly solstice
#

Hey quick question guys: If i have a string that looks like this for example Fhttps://temporaryimport.ams3.digitaloceanspaces.com/metadata/6848.json is there a way ( besides something like link = link[1:71]) to cut out the link by saying start with https and end with .json? So its easier scalable

rare saddle
#

How to make a link in an embed title?

worldly solstice
worldly solstice
#

just embed.set_url

worldly solstice
rare saddle
#

Am I doing something wrong?

stone beacon
#

You need to add TextInput to the modal (the form)

#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0...
stone beacon
#

That's what you need to use, not View for your form @gaunt mortar

gaunt mortar
stone beacon
vale wing
unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

google.com
stone beacon
#

Since when can we use !e here 👀

vale wing
#

If you meant this

#

You can extract any part just by splitting your link

stone beacon
#

!e

link = "https://temporaryimport.ams3.digitaloceanspaces.com/metadata/6848.json"
print(link.startswith("https://") and link.endswith(".json"))
unkempt canyonBOT
#

@stone beacon :white_check_mark: Your eval job has completed with return code 0.

True
sick birch
stone beacon
#

Although wrong channel mb

stone beacon
sick birch
#

yup

heavy shard
#

the world is so huge, there's nothing on it that wouldn't exist

quaint forum
#

Did discord just break image embeds or something? I didn't change anything here and the images arent in the embeds anymore... The code is retrieving the image just fine; I'm having it print it out in the output, but its just not putting the image into the embed, any ideas? I'm going to try to undo a bunch of stuff I just did to see if thats why, but I really don't think it is

heady sluice
#

how do you set it

quaint forum
#

Like this, the same way I was setting it 30 minutes ago when it was working

embed.set_image(url=currentWinner.attachments[0].url)

heady sluice
#

did you print currentWinner.attachments[0].url ?

quaint forum
#

yep

#

is it cause the file .PNG?

heady sluice
#

seems good

quaint forum
#

someone just told me its supposed to be .png

heady sluice
#

even though Idk why png is uppercase

quaint forum
#

yeah i dont either

#

I think its cause of the caps, my friend just sent a .png instead of .PNG and his worked just fine

heady sluice
#

try
embed.set_image(url=currentWinner.attachments[0].url.lower()) then

quaint forum
#

well maybe not, my .PNG is working now, I think discord just had a really temporary problem lol

heady sluice
slate swan
#

So i'm wanting to put info into an embed, but i want to get the information from the databse about that specifc trade, i tried this but it didnt work:
py trade = mycursor.fetch(f"SELECT trade FROM t_info WHERE channelID = {message.channell.id}")

heady sluice
heady sluice
#

and that's embarrassing

#

little note

slate swan
#

depression , its been a hard day at school

heady sluice
#

what db is this?

slate swan
#

mysql

heady sluice
#

nah then you don't need my note which would've been using parametrized queries

cloud dawn
#

!tags

heady sluice
#

!repl

unkempt canyonBOT
#

Read-Eval-Print Loop

A REPL is an interactive language shell environment. It first reads one or more expressions entered by the user, evaluates it, yields the result, and prints it out to the user. It will then loop back to the read step.

To use python's REPL, execute the interpreter with no arguments. This will drop you into the interactive interpreter shell, print out some relevant information, and then prompt you with the primary prompt >>>. At this point it is waiting for your input.

Firstly you can start typing in some valid python expressions, pressing <return> to either bring you to the eval step, or prompting you with the secondary prompt ... (or no prompt at all depending on your environment), meaning your expression isn't yet terminated and it's waiting for more input. This is useful for code that requires multiple lines like loops, functions, and classes. If you reach the secondary prompt in a clause that can have an arbitrary amount of expressions, you can terminate it by pressing <return> on a blank line. In other words, for the last expression you write in the clause, <return> must be pressed twice in a row.

Alternatively, you can make use of the builtin help() function. help(thing) to get help on some thing object, or help() to start an interactive help session. This mode is extremely powerful, read the instructions when first entering the session to learn how to use it.

Lastly you can run your code with the -i flag to execute your code normally, but be dropped into the REPL once execution is finished, giving you access to all your global variables/functions in the REPL.

To exit either a help session, or normal REPL prompt, you must send an EOF signal to the prompt. In *nix systems, this is done with ctrl + D, and in windows systems it is ctrl + Z. You can also exit the normal REPL prompt with the dedicated functions exit() or quit().

unkempt canyonBOT
#

SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also
Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
PEP-249 - A specification of how database libraries in Python should work

heady sluice
#

uh this is unexpected

heady sluice
cloud dawn
heady sluice
#

oh

cloud dawn
#

Every coding language

heady sluice
#

misleading pinned message

slate swan
sick birch
heady sluice
#

on channel

cloud dawn
slate swan
heady sluice
#

you didn't tell us what the error is

slate swan
#

AttributeError: 'CMySQLCursor' object has no attribute 'fetch'

cloud dawn
#

I thought it would be that error.

#

It's fetchone or fetchall

heavy shard
#

maybe fetchone or fetchall

olive osprey
#

Hey,
I'm currently testing around a bit on slash autocompleting, and I run into this problem:
https://i.imgur.com/XZgakum.png
The code is (obviously) supposed to send the embed, and not the object. I don't really know what I did wrong, as I also can't await it before which I think would fix the problem. This is my current code:

This is the ruleclass, I'm following the docs where they mentioned to subclass it:

class ruleclass(str, Enum):
    RuleOne = disnake.Embed(title="1) Follow the Discord ToS (https://discord.com/terms)", color=disnake.Colour.random())

This is the command:

    @commands.slash_command(description="Send a specific rule into the channel.")
    async def ruletest(
      inter: disnake.ApplicationCommandInteraction,
      rule: ruleclass
    ):
      await inter.response.send_message(rule)
heady sluice
#

it's embed=rule

olive osprey
#

Bruh, sometimes I think I'm missing the half of my brain

heady sluice
#

that's unfortunate

vocal plover
#

I'm missing all 3 halves of my brain tbh

heady sluice
#

that's interesting

slate swan
cloud dawn
cloud dawn
slate swan
#

database or python wise?

heady sluice
#

py

heavy shard
#

same error? no such attribute?

slate swan
#

pycord

slate swan
heady sluice
#

bru he didn't mean the discord library

slate swan
#

oh

vocal plover
#

so why did you say py not database lol

heady sluice
#

python wise doesn't mean discord wise

vocal plover
#

I mean sure but like, isnt database the only option there for the db lib anyway lol

heady sluice
#

@slate swan you got an answer in databases

#

I guess

slate swan
#

ill try and see if it works

heady sluice
#

not this

#

even though I don't think the answer he got makes sense

#

in databases

cloud dawn
slate swan
#

Does anyone know how to go back to other python versions as my bot only runs on 3.8.12?

heady sluice
#

!e
print("hello".hellobello())

unkempt canyonBOT
#

@heady sluice :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: 'str' object has no attribute 'hellobello'
slate swan
#

wdym only runs on 3.8.12?

heady sluice
#

attributeerror

slate swan
slate swan
slate swan
#

what, what makes you say that?

cloud dawn
slate swan
slate swan
slate swan
slate swan
#

what errors do you face?

slate swan
frozen patio
heady sluice
#

I have asyncpg and it's working pretty damn well

frozen patio
#

I use a few

#

Like SQLAlchemy

#

for webserver databases

#

then SQLite for bots

#

🤔

heady sluice
#

I wanna get into js to make websites

#

and maybe switch to djs

frozen patio
#

Meh

heady sluice
frozen patio
#

Also used JS to start my first public website

vocal plover
#

svelte is cool for that

frozen patio
#

It wasn't too bad in JS

flint isle
#

In:

    @commands.Cog.listener()
    async def on_command_error(self, ctx: commands.Context, error: disnake.ext.commands.CommandError):
        try:
           await ctx.send(error)
           print(Fore.RED + '[Error]' + Fore.WHITE + f"{error}")
        except BaseException:
            print('Error has occurred in error handler! All hope is lost! You may panic!') # hope this code never executes 

How can I push a help dialog for the command with an issue so they can see the syntax

heady sluice
#

why are you using try-except in an error handler

#

well it doesn't matter

flint isle
#

it's what was reccomended to me earlier. ¯\_(ツ)_/¯

heady sluice
#

what do you mean by help dialog?

#

just how to use the command?

flint isle
#

Like

$cmd {argnamehere}
#

On an error.

#

So they run $cmd but forget the arg so it sends the syntax to remind them

heady sluice
#

hm, all you need is the Command object which I'm trying to see how you get with the Error

#

!d discord.ext.commands.Context.command

unkempt canyonBOT
heady sluice
#

!d discord.ext.commands.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the
decorator or functional interface.
heady sluice
#

these are the attributes of ctx.command

#

you could send ctx.command.usage

#

it seems useful

flint isle
#

So

await ctx.send(ctx.command.usage)```
heady sluice
#

probably

grand shell
#
@commands.Cog.listener()
    async def on_message(self, message):
        if not message.channel.category:
            return
        if message.channel.category.name != self.categoryName:
            return
        if self.botPrevention and message.author.bot:
            return

        for channel in self.channels_to_send(message):
            if len(await channel.webhooks()) < 1:
                await channel.create_webhook(name="test")

            webhook = (await channel.webhooks())[0]
            await webhook.send(message.content, username=message.author.name, avatar_url=message.author.avatar.url)```
hey guys, i have this code that essentially sends the same message a user sent in multiple channels using a webhook. it all works but when people spam there is some pretty major delay between someone sending the message and the webhook sending it in the other channels. is the bottleneck in discord's servers due to too many requests? is it on  my end? if i host it on a beefier server will it be faster?
flint isle
flint isle
flint isle
grand shell
#

so is there anything i can do?

flint isle
#

Nope. What's it for anyways lol

grand shell
#

so what do really huge bots do (like MEE6) and so on

#

surely they are doing more than 50 API requests / second (which is the limit i think)

vale wing
#

Huge bots have higher limits

grand shell
#

ah ok

#

is there a formal proccess to increasing your bots limit?

#

like once you reach x servers you get x requests/s

sick birch
#

Other than just growing larger, no

vale wing
#

I don't know myself but it must be automated

#

The only formal thing you gotta do with your bot is to verify it on 100 guilds

grand shell
#

yea

#

rip

heady sluice
vale wing
#

I just checked dev portal and it turns out limit of 50 requests per second is global tho

#

Weird I have other information

waxen python
#

I have a function in a cog file, that i need to call with data from another file thats not apart of the bot.
Problem is, it has self. And using @staticmethod doesnt work as in the function in the bot file i need to use client.
How can I call the function without self?

vale wing
#

Could you show the whole function

waxen python
#
    async def crisp_chat_received(self, channel_name, raw_data):
        WH_guild = self.client.get_guild(0000000000000000000)
        try:
            send_to = discord.utils.get(WH_guild.channels, name=channel_name)
            await send_to.send(f"From: {raw_data['data']['user']['nickname']}\n {raw_data['data']['content']}")
        except Exception as e:
            print(e)
            print("Channel not there, will make!!!!")
            print(channel_name)
#

oops, sorry

vale wing
#

Just parse client to a function

#

You don't need the whole cog

waxen python
#

The file thats calling the function doesnt have client, its not apart of the bot core (the file with the image code)

vale wing
#
# file1
async def crisp_chat_received(client, channel_name, raw_data):
    ...

# cog
await crisp_chat_revived(self.client, ..., ...)```
waxen python
#

Its the other way around

# external file
asyncio.run(crispAPI.crisp_chat_received(channel_name, data))

# cog
    async def crisp_chat_received(self, channel_name, raw_data):
        WH_guild = self.client.get_guild(0000000000000000000)
        try:
            send_to = discord.utils.get(WH_guild.channels, name=channel_name)
            await send_to.send(f"From: {raw_data['data']['user']['nickname']}\n {raw_data['data']['content']}")
        except Exception as e:
            print(e)
            print("Channel not there, will make!!!!")
            print(channel_name)
vale wing
#

Why the heck is there asyncio.run

waxen python
#

because its an async function

vale wing
#

I don't get the purpose of it

sick birch
#

It’s the recommended way

vale wing
#

Why wouldn't you just await it

waxen python
#

i dont think that would help

vale wing
#

To help with that I need to know the project structure

pliant gulch
#

If you have no access to the Bot abstraction, you’ll have to use the REST api manually. Seems like you have the proper IDs anyways to make that work

vale wing
#

Pretty sure you are able to make the whole thing awaitable without usages of asyncio.run and other utilities to run coro from non coro context

waxen python
#

okay

bot {
     cog.py (has crisp_chat_received function)
}
    @webserver-event (needs to fire crisp_chat_function)
}
vale wing
#

Ah API integration?

waxen python
#

yes

vale wing
#

Personally I just put the whole API into a cog

waxen python
#

Wait, no im not sure i meant that
its processing a webhook

pliant gulch
#

If it’s a webhook you won’t need the bot either

vale wing
waxen python
#

the webhook has the json data the bot needs to do my thing

vale wing
#

But I am guessing you are having issues specifically with API integration

waxen python
#

the issue im having is getting the data from the webserver passed to the function in the cog

vale wing
#

So the solution is

  1. Bring the function out to a separated module

  2. Put your API into another cog so you can access the bot from it

#

Outdated tutorial don't watch it

waxen python
#

I cant really bring the function out (i dont think) because i need to interact with discord, like creating channels/sending messages as the bot with the json response from the webserver

vale wing
#

Everything > 1 year old is outdated and the other part is mostly incorrect

#

Proper way to get a channel*

pliant gulch
vale wing
#

!d discord.Guild.get_channel (bot has this method as well)

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads...
vale wing
#

Yes

waxen python
vale wing
#

Just parse client arg to there

#

You can always bring a piece of code to a function

waxen python
#

client arg from where tho? I dont have it in the external file that im passing from

vale wing
#

There are no exceptions

waxen python
#

but it needs to go

#

im unsure how that would work

vale wing
#

That's called refactoring

waxen python
#

that doesnt seem to solve the issue if i need client from the cog to pass to another external file

pliant gulch
vale wing
#

Second point

#

Put your API into the cog

#

Another cog*

waxen python
#

its not an API, its a webserver

vale wing
#

Same thing

pliant gulch
#

The create message endpoint is just POST channels/channel_id/messages then you pass the payload

#

Authorisation headers r needed as well but you I’m assuming have the token

#

The only other thing you need is an aiohttp session

waxen python
# vale wing From cog

currently / (what i would like):
external file (has data needed in cog) -> cog (has client to interact with discord, uses data from webserver in a function in the cog)

pliant gulch
#

Do you start the bot and the web server in the same file?

waxen python
pliant gulch
#

Instead of making it do a process open just import the file and run it from the same file

#

Then you’ll have access to the bot instance

sick birch
#

Look into threading

#

You can share resources between threads iirc

#

If you’re making a dashboard, consider if you need IPC between bot and dashboard