#discord-bots

1 messages · Page 837 of 1

tall walrus
#

Linux

pliant gulch
#

That's odd, add_signal_handler should work fine for linux

#

I was expecting windows or something

tall walrus
#

idk

#

When I test on Windows everything works fine though

pliant gulch
#

Since you sublcasses the client already, you could just overwrite the run method bound to the class, and just call self.loop.stop() after calling the super classes run method

#

That would probably fix the error, or in this case handle closing the client correctly

tall walrus
#

Ok I will try

#

Thanks for your help anyways

#

Where do I place the command self.loop.stop() ?

pliant gulch
#

You would overwrite the run method, call super().run(...) ... being whatever args you were gonna give to bot.run, You'd wrap super().run(...) in a try-except with RuntimeError then call self.loop.stop() if caught

#

You may then call self.loop.close() afterwards, which discord.py was originally attempting to do

tall walrus
#

I have this error now :

NameError: name 'self' is not defined```
pliant gulch
#

You have to create the method bound to the subclassed client class

#

Pass self to the arguments as the first arg

slim ibex
#

self should be the first parameter of instance methods

#

class methods take cls and static methods don’t need any params

tall walrus
#

okay

#

If not, can you fix the code? I admit I'm a little confused especially since I don't speak English fluently so it's hard to understand what you're saying.

slim ibex
#

we won’t spoon feed, but we will help you

tall walrus
#

okay

cerulean olive
#

Failed to load the developer.py cog. Exception: Extension 'cogs.developer' raised an error: AttributeError: module 'utils' has no attribute 'CustomContext'

#

from contextlib import redirect_stdout
from typing import List, Optional
import discord, json, utils, traceback, textwrap, io
from discord.ext import commands
from discord import Embed


my imports and stuff

slim ibex
#

had nothing to do with imports

cerulean olive
#

idk i have confused my self

slim ibex
#

well

#

it says your utils module

#

So I assume you are trying to use a name from there that doesn’t exist

cerulean olive
#

as well

#

'cogs.misc' raised an error: AttributeError: module 'discord' has no attribute 'ui'

#

i am learning cogs

hoary cargo
#

Are you using dpy 1.7.x ? Or

slim ibex
#

!pip discord-ui

unkempt canyonBOT
hoary cargo
#

Wack

slim ibex
#

forks like disnake don’t require you to install extra shit for things like interaction. I would migrate over as it isn’t a big code change

cerulean olive
#

whats a short way 2 search for a command

slim ibex
#

wdym

cerulean olive
#

like u can search for a command name'

slim ibex
#

in discord?

cerulean olive
#

in vsc

slim ibex
#

CTRL+F and search for the function?

cerulean olive
#

thanks

hoary cargo
pliant gulch
#

pycharm kek

cerulean olive
#

yea these are just all my errors i got 2 fix

[-] Failed to load the developer.py cog. Exception: Extension 'cogs.developer' raised an error: AttributeError: module 'utils' has no attribute 'CustomContext'

[-] Failed to load the misc.py cog. Exception: Extension 'cogs.misc' raised an error: AttributeError: module 'discord' has no attribute 'ui'

[-] Failed to load the moderation.py cog. Exception: Extension 'cogs.moderation' raised an error: AttributeError: module 'utils' has no attribute 'CustomContext'

[-] Failed to load the reminder.py cog. Exception: Extension 'cogs.reminder' raised an error: AttributeError: module 'utils' has no attribute 'CustomBot'
#

@slim ibex can u add me

boreal ravine
maiden fable
#

I smell copied code 👀

hoary cargo
tidal hawk
#

How to avoid InteractionResponded error, but still be available to edit the interaction

maiden fable
#

use interaction.defer then interaction.followup

tidal hawk
maiden fable
#
Traceback (most recent call last):
  File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/client.py", line 693, in connect
    self.ws = await asyncio.wait_for(coro, timeout=60.0)
  File "/usr/local/lib/python3.10/asyncio/tasks.py", line 445, in wait_for
    return fut.result()
  File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/gateway.py", line 428, in from_client
    gateway = gateway or await client.http.get_gateway()
  File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/http.py", line 2391, in get_gateway
    data = await self.request(Route("GET", "/gateway"))
  File "/pufferpanel/.local/lib/python3.10/site-packages/disnake/http.py", line 343, in request
    async with self.__session.request(method, url, **kwargs) as response:
  File "/pufferpanel/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1138, in __aenter__
    self._resp = await self._coro
  File "/pufferpanel/.local/lib/python3.10/site-packages/aiohttp/client.py", line 559, in _request
    await resp.start(conn)
  File "/pufferpanel/.local/lib/python3.10/site-packages/aiohttp/client_reqrep.py", line 898, in start
    message, payload = await protocol.read()  # type: ignore[union-attr]
  File "/pufferpanel/.local/lib/python3.10/site-packages/aiohttp/streams.py", line 616, in read
    await self._waiter
aiohttp.client_exceptions.ClientOSError: [Errno 104] Connection reset by peer

@pliant gulch do u know why this error is there?

spring fjord
#

How to get started with this bot in python ,any online material anyone could suggest

maiden fable
# tidal hawk

interaction.followup can be used to edit or send whatever

#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

tidal hawk
#

ah so interaction.followup.edit_message?

cedar stream
#

!unban

maiden fable
#

sure

#

!source unban @cedar stream

unkempt canyonBOT
#
Command: unban

Prematurely end the active ban infraction for the user.

Source Code
cedar stream
hoary cargo
maiden fable
cedar stream
cedar stream
maiden fable
#

Haha

pliant gulch
pliant gulch
maiden fable
pliant gulch
maiden fable
pliant gulch
maiden fable
maiden fable
slate swan
#

can a command be triggered by a slash or it's prefix at the same time? (disnake)

maiden fable
#

Sure

#

Just define two separate commands

pliant gulch
maiden fable
#

I don't use those ngl

potent spear
#

That was one of my first errors
since pycharm automatically starts a project in a venv & I was installing globally

slate swan
maiden fable
#

Sure

potent spear
tidal hawk
#

Should I use interaction defer before or after respondid the message

hoary cargo
hoary cargo
# maiden fable Lmaoo

also if you really have a problem with this you can make that the venv inherits the modules from your other projects but well peeposhrug

maiden fable
cerulean olive
maiden fable
cerulean olive
maiden fable
cerulean olive
pliant gulch
#

Pycharm, the IDE that does 20 other things you don’t need

potent spear
#

pass the requirements.txt I'd say

tidal hawk
#

@maiden fable pls guide me how to use that followup

#

obv that way it doesnt work

maiden fable
#

u need to do send

#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., view=..., tts=False, ephemeral=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
tidal hawk
#

But i want to edit the message

maiden fable
#

Which message lol

tidal hawk
#

Firstly it's inside a dropdown menu

#

then after selecting something it will add another view with buttonis

maiden fable
#

Then remove the defer and just do interaction.response.send_message and then use interaction.response.edit_original_message

tidal hawk
#

I think that was the thing I was searching for

cerulean olive
#

whats best way 2 learn cogs

maiden fable
#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
tidal hawk
#

And If I want to respond with nothing (to avoid the Interaction Failed) then I just respond with defer right?

#

or is there another way

hoary cargo
tidal hawk
#

How are there multiple views on one message?

kindred drum
#

yo anyone know how I would check an account age?

#

like compared it e.g. if account age < 3 months then:

slate swan
#

ok imma make a new bot so in a few hours i might need help

maiden fable
#

U can add multiple components in the same view

hoary cargo
unkempt canyonBOT
#

property created_at```
Equivalent to [`User.created_at`](https://docs.disnake.dev/en/latest/api.html#disnake.User.created_at "disnake.User.created_at")
kindred drum
#

anyone know how to like get the account age from the creation date?

#

it seems really complex but if anyone got a good idea lmk

maiden fable
#

Wait what

#

account age from creation date?

#

Ah u mean the time how old the account is?

kindred drum
#

yeah

#

like 1 year old etc

maiden fable
#

Well, there was a function like that in the datetime lib

hoary cargo
fallow mauve
#

how to do cooldown messages?

naive spoke
#
@client.command()
async def test(ctx):
    await ctx.send('click here for roles')
    await message.add_reaction(':white_check_mark:')

why is the reaction not on the message

buoyant quail
naive spoke
buoyant quail
#

message = value

naive spoke
#

uh

honest vessel
#

message = await ctx.send('click here for roles')

naive spoke
#

i didnt do message

#

oh

honest vessel
#

you need to define variable as that ctx.send and it will be a message object that u then can use with .add_reaction() on

naive spoke
#

i see

#

await message.add_reaction(':white_check_mark:') message does not have anything

honest vessel
#

did you change the code?

naive spoke
#

i just did lemme see

#

uh still no reaction i put in message =

@client.command()
async def test(ctx):
  message =  await ctx.send('click here for roles')
  await message.add_reaction(':white_check_mark:')
honest vessel
#

ah you cant do ✅

#

you need unicode

naive spoke
#

which is?

honest vessel
#

\✅

#
@client.command()
async def test(ctx):
  message =  await ctx.send('click here for roles')
  await message.add_reaction('✅')
naive spoke
#

yea it works

#

now how do i make it that the bot says somthing when we click reaction

honest vessel
#

@naive spokehint ow to get unicodes of emijis in discord type :emojiname: but put \ infront of the emoji and post it

naive spoke
#

k

honest vessel
#

if you copy ✅ it will not be unicode it will copy : white_check_mark :

#

but if u put \ infront of emoji it will post a unicode one

naive spoke
#

no i mean

#

copy to vscode

honest vessel
#

ah yea

honest vessel
# fallow mauve how to do cooldown messages?

for messages as posted by a user? then you will need to track them and put em with time and if like X messages in Y time: put timeout / ignore messages for a cooldown, this would be best done in a database

fallow mauve
#

ok

honest vessel
#

but if you want cooldown for commands there are @decorations @command.cooldown()

fallow mauve
#

thx

nimble plume
#

Need a idea

naive spoke
#

ok how do i make the bot reconize a reaction and the user who did it and send a message

honest vessel
nimble plume
#

I have a !prvc create command which creates a channel and add author id to a list i want to check if the channel is deleted the user id is removed suggest something

#

Datamanagment smh

honest vessel
#

or you can use wait_for()

naive spoke
#

um

final iron
unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
kindred drum
#

member.created_at.timestamp?

nimble plume
#

logs = some of database
for items in logs
If payload.guild.id == logs
await ctx.send(guild somehow)

#

payload.guild.send()

#

.channel*

honest vessel
nimble plume
#

Nvmd

nimble plume
#

If im not wrong

honest vessel
#

wich makes it easier to edit and manage ur bot, and also disable/activiate diffrent commands

kindred drum
tiny ibex
#
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\phoen\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\client.py", line 515, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\phoen\OneDrive\Desktop\nox-bot\main.py", line 123, in on_command_error
    raise(error)
  File "C:\Users\phoen\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot_base.py", line 561, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\phoen\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 930, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\phoen\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 185, in wrapped
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'name'
#

Whyyyyyyyy

final iron
nimble plume
#

Code

tiny ibex
#
@bot.command(name='snipe')
async def snipe(ctx):
    channel = ctx.channel
    try:  #This piece of code is run if the bot finds anything in the dictionary
        channel_name = channel.name

        em = disnake.Embed(name=f"Last deleted message in #{channel_name}",
                           description=snipe_message_content[channel.id])
        em.set_footer(
            text=f"This message was sent by {snipe_message_author[channel.id]}"
        )
        await ctx.send(embed=em)
    except KeyError:  #This piece of code is run if the bot doesn't find anything in the dictionary
        await ctx.send(
            f"There are no recently deleted messages in #{channel.name}")```
honest vessel
tiny ibex
#
@bot.event
async def on_message_delete(message):
    snipe_message_author[message.channel.id] = message.author
    snipe_message_content[message.channel.id] = message.content
    await asyncio.sleep(60)
    del snipe_message_author[message.channel.id]
    del snipe_message_content[message.channel.id]```
kindred drum
final iron
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
nimble plume
#

kwarg

tiny ibex
honest vessel
kindred drum
#

t:1609864241.184:R

tiny ibex
#

I was using old discord version

honest vessel
#

<t:t:1609864241.184:R>

#

<t:1609864241.184:R>

tiny ibex
honest vessel
#

<t:1609864241:R>

tiny ibex
honest vessel
#

yeah remove decimals

kindred drum
#

<t:1609864241184:R>

tiny ibex
#

You can use Math.trunc

kindred drum
#

how do I remove decimals 😦

final iron
#

<t:9462829>
Is:
<t:8462829>

honest vessel
#

u can use round(thetimestamp)

tiny ibex
final iron
unkempt canyonBOT
#

round(number[, ndigits])```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.

For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.

For a general Python object `number`, `round` delegates to `number.__round__`.
kindred drum
tiny ibex
#

F

kindred drum
#

?

honest vessel
#

round(datetime()) 😛

final iron
#

!e
print(round(1609864241.184))

unkempt canyonBOT
#

@final iron :white_check_mark: Your eval job has completed with return code 0.

1609864241
honest vessel
#

<t:1609864241:R>

#

<t:1609864241:F>

#

replace :R with :F for that second format

kindred drum
#

awesome

#

how do I get it like saying 1 year, 3 months

honest vessel
#

well with this build in converter i guess it only say a year ago

#

or 2 years ago etc

kindred drum
#

oof

#

<t:3412:R>

#

<t:3:R>

honest vessel
#

you will have to make your own but you can print both formats and it specifies

kindred drum
#

bruh

#

how do I get less than a year

final iron
#

There are more formats

kindred drum
#

<t:12321321312312:R>

#

<t:0.33:R>

#

<t:1.33:R>

honest vessel
#

!e
import time
print(time.time())

unkempt canyonBOT
#

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

1645199827.5217543
kindred drum
#

<t:1:R>

#

<t:0.33:f>

honest vessel
#

<t:1645199827:R>

kindred drum
#

<t:333:f>

final iron
honest vessel
#

1645199827

honest vessel
#

how manyh seconds has been since that date n time

kindred drum
#

oof

honest vessel
#

<t:0:F>

#

^ = 0

#

1645199827 seconds <-- sum min ago

kindred drum
#

oof k

honest vessel
#

that is a question they should use on "who wants to be a millionare" or something 😄 what date n time is unixtime 0

oak warren
#

use datetime

#

and .timestamp()

#

and trunc it

#

and use

#

dpy has inbuilt converty ( 2.0 only )

#

if you use any fork its there for you already

slate swan
#

quick question. is there a way that i can remove the cooldown py @client.command() @commands.cooldown(1,60,commands.BucketType.user) async def test(ctx, *,arg=None): if arg is None: #removes the cooldown from the command #other codes here

oak warren
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.9)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
oak warren
unkempt canyonBOT
oak warren
#

np

honest vessel
#

i think that resets for all users tho

lavish axle
#

!e

unkempt canyonBOT
#
Command Help

!eval [code]
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

lavish axle
#

!e generator

unkempt canyonBOT
#

@lavish axle :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'generator' is not defined
honest vessel
#

lol?

lavish axle
#

Hmm

#

!e print(""Hello world")

unkempt canyonBOT
#

@lavish axle :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print(""Hello world")
003 |           ^^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
honest vessel
#

lol

lavish axle
#

Lmao

#

!e print("Hello")

unkempt canyonBOT
#

@lavish axle :white_check_mark: Your eval job has completed with return code 0.

Hello
lavish axle
#

!e i = []

unkempt canyonBOT
#

@lavish axle :warning: Your eval job has completed with return code 0.

[No output]
honest vessel
#

!e
while 1:
print("LOL")

unkempt canyonBOT
#

@honest vessel :x: Your eval job has completed with return code 143 (SIGTERM).

001 | LOL
002 | LOL
003 | LOL
004 | LOL
005 | LOL
006 | LOL
007 | LOL
008 | LOL
009 | LOL
010 | LOL
011 | LOL
... (truncated - too many lines)

Full output: too long to upload

honest vessel
#

xD

manic wing
#

#bot-commands

slate swan
#

um, @honest vessel you okay?

maiden fable
#

Seems like he is drunk

honest vessel
lavish axle
#

!e
for i in range:
print("LMAOOO")

unkempt canyonBOT
#

@lavish axle :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: 'type' object is not iterable
lavish axle
#

Wat

slate swan
honest vessel
#

u had space infront of ur for loop

honest vessel
maiden fable
#

Yea he is totally drunk rn

honest vessel
#

😦

slate swan
slate swan
maiden fable
slate swan
#

anyways

maiden fable
#

Anyways

slate swan
#

!ot

unkempt canyonBOT
maiden fable
#

Knew it

slate swan
maiden fable
#

Nowadays, yes

#

Imagine getting this for free 😶

maiden fable
#

And using it in your discord bot

slate swan
maiden fable
#

in the code

final iron
maiden fable
#

I mean

#

Yea, according to me at least xD

final iron
#

Isn't 3 tables like nothing though?

maiden fable
#

I am talking about the reads and writes lol

final iron
#

Oh

honest vessel
maiden fable
#

Lol

honest vessel
#

bbl cigg n beer time

tacit token
#

hello guys, how can i make

 if user2 == None:
        user2 = ctx.author```

If the user none the user == my bot
#

i try slap command with pillow

native wedge
#

what is a good cheap VPS for simple bot? only using on 1-2 servers

honest vessel
#

i use vultr before i used digitalocean

native wedge
#

what is better

honest vessel
honest vessel
native wedge
#

also

#

ive seen in servers

#

multiple of the same bot

#

like how would that work

honest vessel
#

@native wedgemy vultr server, top - 16:51:52 up 373 days

#

more than a year up n running

native wedge
#

like why ? i dont understand

sick birch
#

AWS is also an excellent provider though it's a bit more expensive than the others

native wedge
#

like its the same bot multiple times, how and why

honest vessel
#

that looks not like abuse at all 😛

final iron
honest vessel
#

but he wanted bot as user2 if its none

#

something like user2 = user2 or bot.user?

sage otter
#

ctx.me works

honest vessel
#

ah yeah forgot that one!

sage otter
#

Oracle free tier users be like:

pliant gulch
#

Cloudflare rest only bot

sage otter
honest vessel
#

raspberrypi 😄

pliant gulch
#

More expensive over time compared to renting a cheap VPS

honest vessel
#

not sure about that 😛

#

it takes like zero power

pliant gulch
#

You have to do maintenance, pay Wi-Fi bills, pay electricity bills, you also have to pay for more storage for the more users you get

honest vessel
#

cheap vps cost 5-10$

pliant gulch
honest vessel
#

i have a raspberry laying at home doing nothing atm but sucking electricity

pliant gulch
#

You also don’t have any warranty for corruption etc

honest vessel
#

your ISP dosnt prob have same uptime either 😛

pliant gulch
#

You also don’t have enterprise level security

#

👁️👁️ overall it’s better to get a VPS

honest vessel
#

ofc 😛

#

hide ur raspberry in mcdonalds or some place with free wifi

#

😁

sage otter
#

I’m return you get that mega latency

pliant gulch
#

That probably breaks their Wi-Fi TOS which they can then sue you for

#

👍 genius idea

#

Your ISP also might not be fine with you hosting, they can throttle your bandwidth

left crater
honest vessel
#

that depends on ISP i never had issue with hosting like IRCbots or skypebots at home

pliant gulch
#

Depends on the ISP but still an issue no less

honest vessel
#

ye vps is best option for sure

honest vessel
maiden fable
regal pulsar
#
@bot.command()
async def fight(message, user: discord.Member):

    global fighter
    global fighter2

    embed = discord.Embed(
        description=f"""{message.author.mention} has challenged {user.mention} to a fight!
Do you want to accept or decline? (yes/no)
"""
    )
    await message.channel.send(embed=embed)

    fighter = message.author
    fighter2 = user
    p1hp = 100
    p2hp = 100
    dmg = random.randint(10, 30)

    def start_choice_p1(ch1):
        return ch1.author == fighter2 and ch1 in ("yes", "no")

    ans = await bot.wait_for("message", timeout=60.0, start_choice_p1=start_choice_p1)

    if ans == "yes":

        while p1hp > 0 and p2hp > 0:
            embed = discord.Embed(description=f"{fighter.mention} it is your turn. What would you like to do?")
            await message.channel.send(embed=embed)

            async def choice_p1(p1choice2):
                return message.author == fighter and p1choice2 in ("hit", "kick")

            p1choice2 = await bot.wait_for("message", timeout=60.0, check=choice_p1)

            async def p1move():
                if p1choice2 == "hit":
                    embed = discord.Embed(
                        description=f"You have hit {fighter2.mention} for {dmg}hp! They now have {p2hp - dmg} left!"
                    )
                    await message.channel.send(embed=embed)
                    p2hp -= dmg
tacit token
# left crater what are u trying to make

slap command. if i write me and asnyone the bot send a pic slap. if i add just 1 member the bot slap anyone with pill

@client.command()
async def slap(ctx, user: discord.Member = None,user2: discord.Member = None):
    if user == None:
        user = ctx.author
    if user2 == None:
        user2 = ctx.author
    wanted = Image.open("batman.jpg")
    asset = user.avatar_url_as(size = 128)
    data = BytesIO(await asset.read())
    pfp=Image.open(data)
    pfp = pfp.resize((291,251)) #A kép mérete pxben
    wanted.paste(pfp,(809,321)) #Ez itt a szélesség / magasság. A szélesség az első
    wanted.save("batman1.jpg")

    await ctx.send(file=discord.File("batman1.jpg"))
regal pulsar
#
                else:
                    embed = discord.Embed(
                        description=f"You have kicked {fighter2.mention} for {dmg}hp! They now have {p2hp - dmg} left!"
                    )

                    await message.channel.send(embed=embed)
                    p2hp -= dmg

            embed = discord.Embed(description=f"{message.fighter2.mention} it is your turn. What would you like to do?")
            await message.channel.send(embed=embed)

            async def choice_p2(p2choice2):
                return message.author == fighter2 and p2choice2 in ("hit", "kick")

            p2choice2 = await bot.wait_for("message", timeout=60.0, check=choice_p2)

            async def p2move():
                if p1choice2 == "hit":
                    embed = discord.Embed(
                        description=f"You have hit {fighter.mention} for {dmg}hp! They now have {p1hp - dmg} left!"
                    )
                    await message.channel.send(embed=embed)
                    p2hp -= dmg
                else:
                    embed = discord.Embed(
                        description=f"You have kicked {fighter.mention} for {dmg}hp! They now have {p1hp - dmg} left!"
                    )
                    await message.channel.send(embed=embed)
                    p2hp -= dmg

        if p1hp == 0:
            embed = discord.Embed(description=f"{fighter2.mention} HAS WON!")
            await message.channel.send(embed=embed)
        elif p2hp == 0:
            embed = discord.Embed(description=f"{fighter.mention} HAS WON!")
            await message.channel.send(embed=embed)
    else:
        embed = discord.Embed(description=f"{fighter2.mention} has cancelled the fight!")
        await message.channel.send(embed=embed)

#
@fight.error
async def on_fight_error(message, error):
    if isinstance(error, asyncio.TimeoutError):
        embed = discord.Embed(description=f"Time's up, the match has been forfeited.")
        await message.channel.send(embed=embed)
honest vessel
#

You mean sum ISP chokes the speed?

maiden fable
honest vessel
#

Not discord? u sure its ISP choking it?

regal pulsar
#

fight cmd

honest vessel
#

any errors?

regal pulsar
#

no

#

but

regal pulsar
left crater
honest vessel
regal pulsar
#

i sent it in 3 parts since it was big

left crater
#

this gets the author profile picture

#

then use pillow to edit it

tacit token
#

ik but i try use my bot if the member not call 2 member to the command

left crater
#
        member = ctx.author```
tacit token
#

my commaand work but i dont know how to call my bot pfp if the member is 1

tacit token
left crater
#

well it should work right?

tacit token
tacit token
left crater
#

then what is it

regal pulsar
#

there

#

help anyone?

#

what exactly is wrong with the listener

tacit token
#

so my problem is how to call my bot pfp if the user 2 is none.

#

i send the image

left crater
#

so u want the bots profile picture?

tacit token
#

so the user1 is none the batman is my bot

#

if user1 is a member user1 pfp here

left crater
#

botavater = bot.avatar_url

tacit token
#

ty i try it

left crater
#

or u can use attachments

quick gust
regal pulsar
#

wait_for isnt working

tacit token
#

pm me @regal pulsar

quick gust
#

ch1.content

#

instead of just ch1

#

do that in all other places like p2choice2

#

wherever you're checking the message's content

regal pulsar
#

ah

vale wing
final iron
unkempt canyonBOT
#

Pasting large amounts of code

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

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

final iron
#

Paste all your code in there

vale wing
#
bot.user.display_avatar.url```
The correct way for dpy 2.0 and main forks
quick gust
regal pulsar
final iron
#

Use the one that was given

regal pulsar
regal pulsar
vale wing
#

Why the heck do you name context message

regal pulsar
regal pulsar
final iron
vale wing
#

That might cause misunderstanding

left crater
regal pulsar
vale wing
final iron
regal pulsar
#

i started like a week ago

vale wing
#

According to PEP8 you should give variables descriptive names

vale wing
#

Not even in python, you should name the variables normally in any languages

#

Sorry for bad grammar

final iron
#

Naming Context message, naming a Member object user etc.

regal pulsar
nimble plume
#

Yes i also use user

final iron
vale wing
#

It should be member, cause user is usually discord.User

nimble plume
#

bot is only on servers ¯\_(ツ)_/¯

final iron
#
member = discord.User
user = discord.Member

Or:

member = discord.Member
user = discord.User
#

Which one is more readable

sick birch
#

use the 2nd one, it makes more sense

#

why would a user be a member

nimble plume
#

😎

final iron
#

Proper variable naming matters

nimble plume
#

Ok ill change it its ez only ctrl + f2 and done

final iron
#

Same thing with context. As Exenifix pointed out, message.message can be really confusing and throw off the reader

nimble plume
#

ctx

slate swan
nimble plume
#

import error

final iron
slate swan
# final iron Code?
import os
from discord.ext import commands
import discord

bot = discord.Bot()

@bot.slash_command(
    name="user", 
    description="Find info about tiktok user", 
    guild_ids=[943921571347714109]
)
async def user(
    ctx, 
    username: Option(str, "Enter the username of the user you want to check.", required=True)
):```
final iron
#

huh

#

What library are you using?

#

discord doesn't have slash support

#

Also, requests is blocking

#

Use aiohttp instead

#

!pypi aiohttp

unkempt canyonBOT
regal pulsar
#

well apart from wrong variable names what's the actual error in my code

final iron
#

You never gave any errors

regal pulsar
#

oh i mean bug

#

whats the bug

#

wait_for isnt picking up the msg

final iron
#

It should

#

Do you have an error handler?

#

It might be eating errors

regal pulsar
#

hmm ill try removing it

regal pulsar
# final iron It might be eating errors

ans = await bot.wait_for("message", timeout=60.0, start_choice_p1=start_choice_p1) TypeError: Client.wait_for() got an unexpected keyword argument 'start_choice_p1'

#

says start_choice_p1 isnt an expected arg

final iron
#

There is no start_choice_p1 kwarg

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
regal pulsar
#

ah

regal pulsar
#

now im getting no errors but no output either

quick gust
#

your command error handler will definitely eat up all the errors u dont handle

regal pulsar
#

i removed it

tacit token
#

hi guys how can i send my bot pfp with client.user.avatar_url

final iron
#

Not 2.0 user

#

🗿

tacit token
#

?

tacit storm
tacit token
final iron
#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
tacit storm
tacit token
# slate swan wdym?

i try command with pillow if the user1==none the bot send the bot pfp but if the user1 == none the bot send my pfp

tacit storm
#

use the one i sent, that should work for bot's avatar/

hoary cargo
#

Why would you send bot pfp

tacit storm
tacit token
#
    botpfp=ctx.bot.user.avatar
    if user == None:
        user = botpfp
    if user2 == None:
        user2 = ctx.author
slate swan
#

==

tacit token
hoary cargo
slate swan
#

bot.user.avatar

tacit token
# slate swan bot.user.avatar

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

vale wing
#

You may also try ctx.me.avatar

slate swan
#

.url

vale wing
#

In his code he has the asset so I suggested asset

slate swan
#

yeah

vale wing
#

Also why c code 😳

daring valley
#

how can i convert ctx to SlashContext (slash command)

vale wing
#

Oh mo I smell weird slash commands lib

hoary cargo
# slate swan .url

Depends if he's using something else than dpy
Even dpy 2.0 ig got rid of .url

daring valley
slate swan
vale wing
#

In versions lower than 2.0 it was indeed

...user.avatar_url```
But now it is
```py
...user.avatar.url```
hoary cargo
#

Wasn't that just an alias?

vale wing
#

Not sure

#

Anyways currently you access it only by second method

tacit storm
vale wing
#

And it's better to use display_avatar because avatar for users with default profile is None

sage otter
#

before avatar wasn’t an Asset

tacit storm
vale wing
#

!d discord.User.display_avatar

unkempt canyonBOT
#

property display_avatar: discord.asset.Asset```
Returns the user’s display avatar.

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.
hoary cargo
vale wing
#

Why'd you need that

tacit token
# vale wing Why `ctx.bot`
@client.command()
async def slap(ctx, user: discord.Member=None,user2: discord.Member=None):
    botpfp=client.user.avatar
    if user == None:
        user == botpfp
    if user2 == None:
        user2 = ctx.author
    wanted = Image.open("batman.jpg")
    asset = user2.avatar_url_as(size = 128)
    data = BytesIO(await asset.read())
    pfp=Image.open(data)
    pfp = pfp.resize((291,251)) #A kép mérete pxben
    wanted.paste(pfp,(809,321))
    asset = user.avatar_url_as(size = 128)
    data = BytesIO(await asset.read())
    pfp=Image.open(data)
    pfp = pfp.resize((291,251)) #A kép mérete pxben
    wanted.paste(pfp,(497,115))
    wanted.save("batman1.jpg")
    await ctx.send(file=discord.File("batman1.jpg"))```
vale wing
#

When there's better option

#

Does context even have bot attr

#

!d discord.ext.commands.Context.bot

unkempt canyonBOT
vale wing
#

O

#

@tacit token what version of lib

tacit token
#

dpy lib or pill or what

vale wing
#

Dpy

tacit token
#

1.7.3

hoary cargo
#

but i understand what u say

slate swan
#

i have this for a client.wait_for('reaction_add') check and how do i make it check also if the message is the same py def check_reaction(reaction, user): return user == ctx.author and (str(reaction.emoji) == cross or str(reaction.emoji) == check)

#

reaction.channel ? if thats a thing

#

o

#

its reaction.message

vale wing
manic wing
#

ctx.author

tacit token
vale wing
#

Well at least now it works

#

Maybe you need member.add_roles

slate swan
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

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

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

There should be no ctx

#

As you are adding roles not to yourself

tacit token
maiden fable
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

the file kwarg

#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "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/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
manic wing
#

await channel.send(file=discord.File('./main.py'))

knotty jasper
#

what is a good resource to learn to make discord bots

vale wing
final iron
vale wing
#

And this one is good as well

knotty jasper
#

Thank you both. It looks fun to do.

slate swan
knotty jasper
#

gives me something to do while outside of class to keep up on python code. Im a cybersecurity major so anything helps keep fresh

hoary cargo
maiden fable
#

the channel isn't in any category

left crater
tacit token
#

its not work, but i delete this project.

golden needle
#

im new to coding and im using some code to make a discord bot but when i try to install colarama this error comes up

slate swan
#

And this isnt the right channel

maiden fable
slate swan
maiden fable
#

Its the ANSI color codes

tacit storm
maiden fable
#

use get member please

slate swan
maiden fable
#

don't use fetch

#

Also

tacit storm
#

i agree, it does need to be a default module but it's not made by python officially.

maiden fable
#

that will trigger every time a message is sent

slate swan
maiden fable
#

So u will need to make another check to see if the message channel has no category

maiden fable
unkempt canyonBOT
#

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

Retrieves a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") from a guild ID, and a member ID.

Note

This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.get_member "discord.Guild.get_member") instead.
tacit storm
#

💀

slate swan
maiden fable
#

Hahaha

#

msg.guild.get_member

cold sonnet
#
        await Birthday.bot.db.execute(...)

class Birthday(commands.Cog):
    def __init__(self, bot) -> None:
        self.bot = bot
```AttributeError: type object 'Birthday' has no attribute 'bot'
excusez moi?
maiden fable
#

just check first if msg.channel.category is None

#

Where u using that tho

#

Also u need an instance of the Birthday class

cold sonnet
#

oh well

#

I wanna make this efficient

#

but it's the worst code I've ever written

#

and my raspberry will NOT be able to handle the bullshit it will see here

maiden fable
#

Yea, also u can combine the first two if statements

final iron
#

Just do:

    if msg.channel.category is None or msg.author.bot:
        return
maiden fable
#

if not msg.channel.category lol

final iron
#

¯_(ツ)_/¯

maiden fable
#

code

#

lemme see...

#

weirddddddddd

final iron
#

!d discord.TextChannel.category

unkempt canyonBOT
#

property category: Optional[CategoryChannel]```
The category this channel belongs to.

If there is no category then this is `None`.
final iron
#

Hmm

#

print msg.channel.category

#

Yes

#

See what its returning

#

The function should of been returned

#

No like print(msg.channel.category)

#

Oh yeah

#

Put that at the beginning of the code

#

Because of the exception the print statement isn't being reached

#

No

#

I mean like this: print(msg.channel.category)

tepid siren
#

hi how can I make it so that my dis bot can only read/send msgs in a certain channel?
code:

import discord

my_secret = ''
client = discord.Client()

@client.event
async def on_ready():
    print("USER:{0.user}".format(client))


@client.event
async def on_message(message):
    if message.author == client.user:
        return
client.run(my_secret)
final iron
#

Are you still getting the exception?

#

bruh

#

🗿

final iron
tepid siren
#

?

final iron
#

Do you want your bot to disregard messages in your command or in an on_message event

#

i.e

@bot.command()
async def my_command(ctx: commands.Context):
    ...

Or

@bot.event
async def on_message(message: discord.Message):
    ...
tepid siren
#

on_message event i think

#

ok but how does this help?

#

😄

final iron
#

!d discord.Message.channel

unkempt canyonBOT
cerulean olive
final iron
#

Code?

cerulean olive
#

    @commands.command()
    async def kiss(ctx, *, user: discord.Member=None):
        await ctx.message.delete()
        if user == ctx.author:
            return await ctx.send("You can't kiss yourself... Find someone to kiss *pssh what a loser*")
        if not user:
            return await ctx.send("You need to ping a user to kiss.")
        r = requests.get("https://nekos.life/api/v2/img/kiss")
        res = r.json()
        em = discord.Embed(description=f"{ctx.author.mention} kissing <3 {user.mention}", color=0x89CFF0)
        em.set_image(url=res['url'])
        em.set_footer(
            text=f"Request by {ctx.author}", icon_url=ctx.author.avatar.url)
        await ctx.send(embed=em)
#

i am using old version of py btw

final iron
#

You need self as the first parameter in your function

#

You're in a class

cerulean olive
#

thank u

#

pov ur a noob

royal meteor
#

Does paginator already have a set amount of commands per page?

final iron
royal meteor
#

Paginator in general

final iron
#

bor

royal meteor
#

I use this

final iron
#

Doesn't mean anything to me

#

It's just a class

royal meteor
#

Does it have a pages arg

final iron
#

idk

royal meteor
final iron
#

!pypi disputils

unkempt canyonBOT
final iron
#

wdym?

#

Are you asking for ways to improve your code?

slate swan
#

hey are you still stuck?

#

send the full code if possible also send what’s happening / what’s not working i don’t see anything glaring in the code above

tepid siren
#
import discord

my_secret = ''
client = discord.Client()

@client.event
async def on_ready():
    print("USER:{0.user}".format(client))


@client.event
async def on_message(message):
    channel = client.get_channel()
    if message.author == client.user:
        return
     if 'hi' in channel.message.content.lower():
        await channel.send('hello')

client.run(my_secret)

hi how can i make this work?

#

i have it in i just deleted it

#

you know just in case

slate swan
#

what output do you get when running it

#

also tell me what you’re indentation looks like that code example i think the tabs are wrong but idk if that’s just a copy/paste discord issue

tepid siren
#

the channel doesn't have the attribute message

#

I need it to detect when a user types something in a certain channel

slate swan
#

print(str(msg))

at the top of your on_message for me

dapper cobalt
#

The channel is not in a category, thus, the channel.category returned as None.

tepid siren
slate swan
#

yeah run it and lmk what output is

tepid siren
slate swan
#

also look at @dapper cobalt they might be right idk

dapper cobalt
#

The print cannot be below the decorator. It has to be inside the function.

#

What comes below the decorator is the function.

vague grove
#

is there an event that can be triggered when someone creates an invite?

slate swan
dapper cobalt
unkempt canyonBOT
#

discord.on_invite_create(invite)```
Called when an [`Invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite "discord.Invite") is created. You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the [`Invite.guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.guild "discord.Invite.guild") and [`Invite.channel`](https://discordpy.readthedocs.io/en/master/api.html#discord.Invite.channel "discord.Invite.channel") attributes will be of [`Object`](https://discordpy.readthedocs.io/en/master/api.html#discord.Object "discord.Object") rather than the respective models.

This requires [`Intents.invites`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.invites "discord.Intents.invites") to be enabled.
tepid siren
slate swan
dapper cobalt
#

Code?

slate swan
# tepid siren yea yea

okay tldr here’s what i’m thinking.

we create a dictionary to track whether or not the bot is allowed to listen in a channel.

you will have a command to toggle letting the bot talk in a channel (on and off)

#

this way you can change the channel / do a different channel / do multiple channels

dapper cobalt
#

If youw ant to print the content of the message, then it's msg.content.

#

The msg param you passed represents a discord.Message.

#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

x != y Checks if two messages are not equal.

hash(x) Returns the message’s hash.
tepid siren
slate swan
tepid siren
slate swan
# tepid siren just one

yeah ez. okay here’s what we’re going to do:

at the top of your file type this:

channelTracking = {}

tepid siren
#

ok

slate swan
#

how to check if something matches the message.content even if it looks likesOmEtHiNg any help?

vague grove
dapper cobalt
#

!d str.lower

unkempt canyonBOT
#

str.lower()```
Return a copy of the string with all the cased characters [4](https://docs.python.org/3/library/stdtypes.html#id15) converted to lowercase.

The lowercasing algorithm used is described in section 3.13 of the Unicode Standard.
tepid siren
slate swan
slate swan
tepid siren
#

ok

tepid siren
dapper cobalt
#

Code?

slate swan
#

@bot.command()
async def workWithChannelTracker(msg):

tepid siren
slate swan
tepid siren
#

kk, now? 😄

slate swan
#

if msg.channel not in channel tracker: #if the channel is not in our dictionary, do this
(Tab)channelTracker[msg.channel] = True
(Tab)await msg.channel.send("added to dictionary and I'm listening")

tepid siren
#

kk

cold sonnet
#

so if I ask you, homies, in a databases case, because the right channel is ded
will I get sent away?
You'd never do that to me

#

homies

slate swan
#

else:
(Tab)if channelTracker[msg.channel]: #if the channel is in our dict but TRUE, we are turning it off
(Tab)(tab)channel tracker[msg.channel] = False
(tab)(tab) await msg.channel.send("no more listening here")

final iron
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

final iron
#

Also you should be using spaces

#

Stop advertising tabs

slate swan
slate swan
#

LMAO

cold sonnet
#
        await db.execute(
            """
                INSERT INTO users (id, birthday) VALUES ($1, $2)
                ON CONFLICT (id) DO UPDATE SET birthday = $2 WHERE (id = $1);
            """, message.author.id, var
        )
  1. can I do that with $1 and $2?
  2. asyncpg.exceptions.AmbiguousColumnError: column reference "id" is ambiguous
#

I will get sent away by Water_Gazes just cuz I said it

final iron
# slate swan LMAO

How does changing `(tabs) into a tab make copy and pasting code any better

slate swan
cold sonnet
#

channel tracker[msg.channel] that's no true code

slate swan
slate swan
slate swan
tepid siren
#

lol

slate swan
#

okay now in your on_message

tepid siren
slate swan
#

if await bot.process_commands(message): #this let’s you try and process the message as a command instead of a message
(tab)pass

#

else:
(put your entire on_message here)

final iron
#

You make 0 sense

slate swan
pliant gulch
#

Why is bot.process_commands in a if statement, do you know that this method always returns None so it is never truthy?

#

And even then, you only pass, this makes no sense

tepid siren
cold sonnet
#

but it never returns a boolean

pliant gulch
#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the message’s author is a bot and doesn’t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
pliant gulch
#

It's bound to your bot instance

slate swan
#

you might be able to skip the pass line BUT this is why

#

we either want it to process as a command OR a message

pliant gulch
#

There should be no pass statement in the first place, neither an if-statement

slate swan
#

not both

tepid siren
#

ummm

slate swan
#

if it’s a command run it, otherwise don’t

pliant gulch
#

You don't process commands 🤔 You process the message

slate swan
#

the message will be the command

fallow mauve
#

ok, im deconstructing my friend's code for his economy bot and attempting to make a bot with it and learn how it works at the same time, and it's been going really well, but i got this error when i tried to add a new section of the user's balance menu:

halcyon sparrow
#

Does anyone feel kind of stuck with starting to code your bot?

slate swan
#

sometimes

pliant gulch
#

Please show me when it is a command

tepid siren
#

bruh

slate swan
#

yes it is you we are implementing it right now

pliant gulch
#

🤔

#

So on_message your message is a Command instance?

slate swan
# tepid siren bruh

ignore them just listen to me still lol it might not be the best way but it’ll work at the end

cold sonnet
#

you process the message and if it runs, it's a command

unkempt canyonBOT
#

Hey @fallow mauve!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
tepid siren
cold sonnet
#

but you don't check if it's a command before processing the message

slate swan
pliant gulch
#

process_commands already does that for you kek

fallow mauve
tepid siren
slate swan
#

without the if/else it runs as command and as message

slate swan
pliant gulch
tepid siren
#

its yellow

pliant gulch
#

But none the less, still runs as you call it

#

The if statement is totally useless, None is not truthy

final iron
#

What is going on here

#

🗿

slate swan
#

that one for sure exists

tepid siren
#

it is spelled right

slate swan
#

bot.process_commands(message)

#

let me see your imports rq

royal meteor
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required```
pliant gulch
# tepid siren

You need to use a commands.Bot instance, from the picture you sent earlier you are using discord.Client which has no commands implementation

tepid siren
slate swan
#

okay add these

fallow mauve
#

nvm, i fixed my problem

slate swan
#

no it’s ez fix dw

pliant gulch
#

You just change your client to commands.Bot and construct it with a command prefix

slate swan
#

from discord.ext import commands
from discord.utils import get

#

add this too^^

pliant gulch
slate swan
#

process_commands() is a method of commands.Bot, if you want to use the commands extension then you should use commands.Bot.

slate swan
pliant gulch
#

🤨

slate swan
#

let us see where it’s at

tepid siren
slate swan
#

send again you were supposed to add a bunch of stuff right?

#

like the new function and imports and stuff

#

ACTUALLY WAIT SORRY okayyy wait here

royal meteor
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.0.value: This field is required```
tepid siren
#

i think im going to give up

pliant gulch
tropic belfry
#

Hi, my bot caches all users, so my bot uses 900mo of ram. I can remove the intent guilds however my bot needs it. What can I do to reduce the ram used?

pliant gulch
unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

1
slate swan
# slate swan else: (put your entire on_message here)

this should be:

else:
(tab)if msg.channel in channelTracker: #if the channel exists as a value in the dict, do this
(tab)(tab)if channelTracker[msg.channel]: #if the value is TRUE, so this:
(tab)(tab)(tab) HERE is where your on_message loop goes

pliant gulch
#

Yea, this works

slate swan
tepid siren
slate swan
#

we’re right at the finish don’t give up yet

#

lmk if that runs, send error if it doesn’t and we’ll fix it

#

we’re gonna get this working rn

pliant gulch
unkempt canyonBOT
#

class discord.MemberCacheFlags(**kwargs)```
Controls the library’s cache policy when it comes to members.

This allows for finer grained control over what members are cached. Note that the bot’s own member is always cached. This class is passed to the `member_cache_flags` parameter in [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").

Due to a quirk in how Discord works, in order to ensure proper cleanup of cache resources it is recommended to have [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") enabled. Otherwise the library cannot know when a member leaves a guild and is thus unable to cleanup after itself.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

The default value is all flags enabled.

New in version 1.5.
pliant gulch
#

You pass this to your bot's constructor

slate swan
final iron
#

Then don't use camelCase?

#

It should never be used in python

slate swan
#

i like camelCase 🥴🥴

pliant gulch
#

🤨

slate swan
final iron
slate swan
#

or just pep standards?

final iron
#

Read the reason pep8 exists

#

Theres your reason

slate swan
final iron
#

There 100% is a reason

#

!pep8

unkempt canyonBOT
#

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
PEP 8 document
Our PEP 8 song! :notes:

pliant gulch
#

Readability is apparently not a valid reason now

final iron
#

If you're not going to follow it, at least don't pass your bad habit on to others

#

You're being an objectively bad guide/teacher right now

royal meteor
#

Is there a way to fix that

pliant gulch
#

Are you saying that the embed size is not matching with the reactions?

royal meteor
#

It does but the length of the pages is a bit long

slate swan
royal meteor
#

Is there a way to make more commands appear on page at once

pliant gulch
#

You can just increase the amount you show in the paginator

slate swan
#

i’m self taught no school or professional training i can sit this one out lol just trying to be helpful

final iron
royal meteor
pliant gulch
#

Not sure what your paginator looks like so I cannot say

final iron
slate swan
#

pep8 is a style guide which all developers should follow

pliant gulch
#

Yea, conventions are important

royal meteor
pliant gulch
#

Imagine you have your finals week, and you have tests all day, but every test is mismatched and there are discrepancies

#

Pretty frustrating right?

cold sonnet
final iron
slate swan
royal meteor
final iron
slate swan
#

ever heard of the python zen?

cold sonnet
#

I think it's okay to not use it if nobody else even sees it

final iron
#

!zen

unkempt canyonBOT
#
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

tropic belfry
final iron
#

It should be used 100% of the time

dull terrace
#

i just use blacken tho

pliant gulch
#

But PEP8 is the most used convention

slate swan
#

Special cases aren't special enough to break the rules. not a rule but not practicing it doesnt seem correct

pliant gulch
dull terrace
#

eww this guide is wrong

royal meteor
dull terrace
#

tabs all the way

pliant gulch
cold sonnet
#

sure

#

I've got plenty of years to practice

final iron
#

I would agree that if you're working on a team with their own special conventions you should follow it (but just for that project/team don't make it a habit)

slate swan
cold sonnet
final iron
#

4 spaces is completely correct

royal meteor
slate swan
dull terrace
#

if by four spaces you mean 1 tab

slate swan
#

like is it an active thing or you just know them at this point

slate swan
final iron
pliant gulch
final iron
#

I also use black

final iron
#

You should be using 4 spaces

dull terrace
final iron
#

Also, you cannot say the guide on the official python website is wrong

slate swan
cold sonnet
pliant gulch
final iron
#

Really nice formatting tool

slate swan
dull terrace
#

yess black is great, i started using it when i learned python and now i pretty much learnt to copy its layout most of the time

final iron
slate swan
vague grove
#

so i have a invite event


@client.event
async def on_invite_create(invite):
    print(invite, invite.guild)

how can I get the invite author? I tried invite.author but to no avail

final iron
#

vsc and pycharm both insert spaces instead of tabs

#

You'll have to figure out if your text editor/ide does it for you

dull terrace
#

it does, but why would it matter even if it didn't

pliant gulch
#

Because code that uses tabs instead of spaces won't work with each other

pliant gulch
#

It's either or

unkempt canyonBOT
dull terrace
#

so you find other sane people that use tabs

pliant gulch
#

Perhaps there are some, you can't say 100% that there isn't

#

But none the less, causes errors because someone isn't following the standard

#

Another reason why PEP8 exists, for good reason too

final iron
#

Developing bad habits is a very bad thing. You don't even realize you're doing it wrong and its very hard to change

slate swan
final iron
#

I already mentioned that

pliant gulch
#

Inb4 switching IDE then commiting code with tabs instead of spaces

cold sonnet
vague grove
dull terrace
#

im not gonna start whacking the spacebar millions of times if i dont need to

final iron
slate swan
#

isnt hard as pep8 says each level of indentation is 4 spaces or a tab that is the same as 4 spaces

final iron
#

Companies do reject applicants who don't follow pep8 a lot

slate swan
#

if you dont know pep8s rules why are you in a job interview anyways?

final iron
#

A lot of people know about them, they just don't care

slate swan
pliant gulch
#

Tab users: It iS OnLy ONe ByTE, Way BeTTER tHAN SPaceS

full lily
cold sonnet
#

im dumb af

vague grove
slate swan
#

a tab isnt considered 4spaces? so its save as one byte?

final iron