#discord-bots

1 messages · Page 931 of 1

slate swan
#

how is that not readable to you?

vocal plover
#

If you go work for someone and you produce code using your methodology I guarantee they won't like you

slate swan
#

Useless argument?

slate swan
vocal plover
#

Nobody wants to do code review where they have to spend half the time trying to understand the flow of your program because it's a mess, before even starting on logic

slate swan
vocal plover
#

"Speaker: Raymond Hettinger

Distillation of knowledge gained from a decade of Python consulting, Python training, code reviews, and serving as a core developer. Learn to avoid some of the hazards of the PEP 8 style guide and learn what really matters for creating beautiful intelligible code.

Slides can be found at: https://speakerdeck.com/...

▶ Play video
tough lance
slate swan
solid summit
#

I think we should stick with the channel's theme here, it's getting out of hand xd

cosmic agate
#

ok im back

#

guys can u tell a good 24/7 hosting service?

slate swan
#

Alright

slate swan
#

im not sure why you guys call this an "argument" when we are having a civilized conversation

cosmic agate
slate swan
slate swan
#

beggars cant be chooserswickedcat

tough lance
#

Aws free trial

cosmic agate
solid summit
#

AWS might do I guess

cosmic agate
slate swan
cosmic agate
#

epik host is gone

cosmic agate
slate swan
#

Lol

slate swan
solid summit
#

wut

slate swan
cosmic agate
slate swan
#

I didnt print..

cosmic agate
#

can anyone give?

ivory cave
#

this is actually so useful i love it, thanks a lot @slate swan

#

<3

slate swan
cosmic agate
slate swan
cosmic agate
slate swan
#

rpi is good as well

slate swan
#
import discord
from discord.ext import commands
from discord.utils import get
import datetime
import requests 

intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix = '>', status=discord.Status.do_not_disturb, intents=intents)

@client.event
async def on_member_join(member):
    guild = client.get_guild(947700821146107944)
    channel = client.get_channel(947701632005705799)
    embed = discord.Embed(
        title = f'{member.name} joined Hercules Snipes',
        description = f"Devved/funded by Donkey#0002"
    )

    embed.set_image(url='https://media.discordapp.net/attachments/948191159317049365/955504065385725963/cropped-herculestitle-banner1.jpg')

    await channel.send(embed=embed)

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

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

    if message.content.startswith('$hello'):
        await message.channel.send('wsg')
    elif message.content.startswith('$mcinfo'):
        username = message.content.split(' ')[1]
        droptime = int(requests.get(f"http://api.star.shopping/droptime/{username}", headers={"User-Agent": "Sniper"}).json()['unix'])

        searches = int(requests.get(f"http://api.droptime.cc/droptime/{username}").json()['searches'])
        await message.channel.send(f'Searches: {searches} | Droptime: {droptime}')

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('Please pass in all requirements :rolling_eyes:.')
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You dont have all the requirements :angry:")

@client.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason = None):
    await member.ban(reason = reason)```
solid summit
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

slate swan
tough lance
ivory cave
# slate swan Overreacted

no its just, ive always wondered how people send such good looking code like that , never knew discord legit has a method made specifically for sending code

slate swan
slate swan
cosmic agate
slate swan
cosmic agate
slate swan
cosmic agate
slate swan
#

im not sure why you guys are overreacting over someone who i helped is grateful?

slate swan
#

Maybe the member role is higher or is administrator

cosmic agate
slate swan
#

Check ur bot perms

tough lance
slate swan
#

Exception

#

Ig

slate swan
#

i stopped reviewing the code when i saw format and f strings in the same snippet

#

where in the code @slate swan

slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
slate swan
vale wing
tough lance
#

Wah here we go again

slate swan
#

isn't that a felony?

pliant gulch
#

Because it totally makes sense to commit a crime just to host a discord bot

vale wing
#

Personally I am gonna do that when I get time

#

😏

tough lance
#

Or just buy a raspberry pi

solid summit
#

Rule 5 screams in pain

vale wing
#

Why buy something when you already have

solid summit
#

Why not have more

vale wing
#

Power

pliant gulch
#

Raspberry Pi and your own server costs more in the end compared to a cheap monthly VPS, but regardless they are fun projects

slate swan
tough lance
#

Btw most people just give up on discord bot coding later so I don't it is a good idea to invest.

solid summit
#

That thing about the rule was a joke no need to delete it haha

slate swan
#

I don't want to get banned 🤷‍♂️

vale wing
#

People barely monetize them

cosmic agate
vale wing
#

I could have done that if stripe wasn't banned in Russia

solid summit
#

Most people do it for fun and it's a pretty good learning method

vale wing
#

Yes

solid summit
#

I started learning dbs because of my bot xd

tough lance
vale wing
#

I even learned docker (almost)

#

Fully agreed that the bot dev gives a lot of knowledge

solid summit
tough lance
#

Ya

#

Not for beginners

vale wing
#

I am now like at level of PCPP-1

tough lance
#

I made the same mistake so ik that

solid summit
#

It worked great for me when attempting to learn asyncio bases

slate swan
#

What worked great

tough lance
slate swan
#

That's not good

solid summit
#

It's a good way of undertanding what you learnt

#

Might not work for everyone tho

tough lance
#

Especially beginners

narrow grail
#

what's the attribute for give role?

vale wing
#

For beginners it won't work at all lmao

vale wing
narrow grail
#

yea

vale wing
#

!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.
narrow grail
#

what is atomic?

vale wing
#

Always wondered what atomic param does

#

Ig when it's true all roles are added within one API call

tough lance
#

Atomic bomb dunno

bleak karma
#

help?

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __call__() missing 1 required positional argument: 'context'```

why does this show up? what causes it?
placid skiff
# narrow grail what's the attribute for give role?

it's not an attribute, it's a method
Learn the difference, attributes are characteristic or properties of a class, most likely are class variables, methods are function that specifies actions of a class

slate swan
# narrow grail what is atomic?

Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

delicate hornet
#

is permission.value the value of permission int?

pliant gulch
#

Atomic operations are just operations that run independent of any other processes

pliant gulch
#

This is a more general programming term, not specific to discord.py

tough lance
vale wing
bleak karma
pliant gulch
#

You learn most of this basic stuff in computer science or something

placid skiff
tough lance
#

It's the same

bleak karma
tough lance
vale wing
#

I am a self learner so uh I might not know something that is given in standard learning programs

placid skiff
spark sentinel
# bleak karma

embed.color = ...
dosen`t exist
embed = discord.Embed(description = "text", color=0x2f3235)

pliant gulch
#

But I have somewhat of a vast background in computer science

vale wing
#

I am literally a musician k

tough lance
#

I just started from biology and planning to become a biomedical engineer

spark sentinel
unkempt canyonBOT
#

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

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

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

New in version 2.0.

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

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
bleak karma
#

but that isnt whats causing the error isnt it

vale wing
pliant gulch
slate swan
tough lance
# bleak karma

It should be because you have same var for your view and your command

vale wing
#

After you finish it you can just explore through docs when you need something

tough lance
vale wing
#

Ah yes

bleak karma
#

oh

vale wing
#

Nice recursion

bleak karma
#

i see lemme change that rq

bleak karma
slate swan
#

hi

#
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
    print(45)
    cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
    base.commit()
    print(1)

    if member is None:
        await ctx.send("Выберите участника")
        return
        
    if reason is None:
       cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
       base.commit()
       print(2222)
       cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
       base.commit()
       await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
    else:
       cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
       base.commit() 
       cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
       base.commit()
        await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")    

not working. Nothing output excepting 45 and 1, why?

#
bot = commands.Bot(command_prefix="pls ")

@bot.event
async def on_member_join(member):
    print("pong")

``` it doesnt do anything
#

doesnt give any errors or output

delicate hornet
slate swan
#

no it does

#

I am sure cuz Im joining with an alt account

delicate hornet
slate swan
#

yeah

idle laurel
#

is there a way i can get my discord bot to message a user privatly when a criteria is met inside a database?

slate swan
#

use tasks

#

to see if criteria is met

#

its in discord.ext

#

import from here and use it like

idle laurel
#

i can sort the criteria being met side, but how do i keep it looping kinda like a listener but not listening for a command

slate swan
#
@tasks.loop(seconds=60)
async def blabla():
  ...
blabla.start()
idle laurel
#

ahh sound one

#

perfect

idle laurel
#

try async def on_member_join():

#

no different like, but im using the same func and it works fine thats weird

south jetty
#

sorry can someone send the docs on renaming channels
cant seem to find it

quick gust
tawdry perch
unkempt canyonBOT
#

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

Edits the channel.

You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
hollow carbon
#

can someone teach me how to see python API

final iron
narrow grail
#

how to delete a command message?

#

and now?

final iron
#

!d discord.ext.commands.Context.message returns a Message object

unkempt canyonBOT
final iron
#

You can then delete it with

#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
narrow grail
#

not with ctx

final iron
narrow grail
final iron
#

Don't see where the issue is

narrow grail
#

I tried ctx.delete()

final iron
#

Yeah you don't do that

final iron
#

You need a message object

slate swan
tidal hawk
#

How can I insert a hyperlink into embe

#

so "link" contains some kind of a link'

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 the Members and Presences intents, which are needed for events such as on_member 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.

cold sonnet
tidal hawk
#

got it

cold sonnet
#

nice

tidal hawk
#

Didn't know how to make it python aswell

#

Thought it's a html thing xd

cold sonnet
#

nah

slate swan
#

the discord client runs in html

tidal hawk
slate swan
#

?

tidal hawk
#

😔

tough lance
#

It's technically the truth

junior verge
#

Is it possible in dpy to have a command name like 8ball in cogs with a number like 8ball

junior verge
#

How?

slate swan
#

just create the command as you would do for any other

#
@commands.command(name='8ball')
async def roll(foo, bar):```
proud fiber
#

How to make a snake game on python?

slate swan
#

you can't name your function 8ball because python functions must start with a letter or an underscore

jolly geyser
#

what is the second part of discord bot token?

river swift
#

nad amas

jolly geyser
#

but what is second

slate swan
quaint epoch
slate swan
junior verge
slate swan
proud fiber
#

Ok ty

jolly geyser
slate swan
slate swan
junior verge
#

thank you

jolly geyser
proud fiber
#

Lol

jolly geyser
slate swan
#

the second part is an unix epoch used for tokens, also encoded to base64

jolly geyser
#

thank you

slate swan
#

and the third part is HMAC, the cryptographic key that is actually used for authentication

jolly geyser
#

is it possible to encode whole token?

slate swan
#

wdym

jolly geyser
#

in python

slate swan
#

yes, you can use python to encode/decode strings

#

but i don't know why you would want to do that

jolly geyser
#

i don't want to go to the discord devolper portal every time when i need my bot's token

#

i want to try to encode it or crack it

jolly geyser
#

idk why

slate swan
brave vessel
#

it does now, no?

jolly geyser
#

nah i have one issue with my pc

slate swan
slate swan
slate swan
#

it only resets when you press the reset button

jolly geyser
slate swan
#

the only discord tokens that reset themselves are used in user authentication

#

which kind of makes this case suspicious

brave vessel
#

i thought it changed, where once you see the token you can't see it anymore and the only way to get a new token is reset

slate swan
slate swan
#

then they changed it in the one month i've been away from pydis

jolly geyser
slate swan
jolly geyser
#

but i don't want to go to the devolper portal every time

slate swan
#

yeah, i see

#

it is indeed like that now

#

still, it shouldn't magically reset on it's own

slate swan
jolly geyser
#

it says like smth like error: repl.it cant find bots TOKEN. please try to add token again or regenerate it

brave vessel
#

you got this token right?

#

you accessed the token from the Bot section

jolly geyser
#

yea

#

no, but it's on replit

slate swan
#

if that's the case, you've gotten a warning each time you pushed to github

jolly geyser
#

replit is almost same as github

slate swan
#

so you've been ignoring it

cold sonnet
slate swan
slate swan
jolly geyser
#

yea

slate swan
#

Then it's fine

#

yeah, it's not because discord is forcing the token to regenerate

brave vessel
#

then how are you reading the token from the env?

slate swan
#

i don't think he actually has it on github

#
  • repl.it doesn't actually support .env files
#

they get converted into their own environment variables tab thing

cold sonnet
#

try running it from an IDE

slate swan
#

and they're automatically encrypted, and loaded in each container

jolly geyser
#

my mom doesn't allow me github idk why

cold sonnet
slate swan
#

don't judge~

cold sonnet
#

I dunno what to say, anyways try running the code from an IDE

jolly geyser
#

ok

unkempt canyonBOT
#

Hey @jolly geyser! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

jolly geyser
#

hmmm

#

may i dm you my token?

#

my bots token

slate swan
#

He doesn't have one

jolly geyser
#

yea

slate swan
#

Yeah, but then he said replit and replit doesn't support that.

jolly geyser
#

i don't have env file because replit does not allow that anymore, but they made env module called secrets and when you click secrets you add name and value

slate swan
#

That works too

jolly geyser
#

no

#

devolper portal regenartes it

slate swan
jolly geyser
slate swan
#

._.

jolly geyser
#

because they are big company and they are busy and these things

#

she says that

slate swan
#

Well, you do have a quite big problem.

jolly geyser
#

13

dull terrace
#

anyone know what characters are disallowed in guild names?

jolly geyser
#

idk sorry

slate swan
#

You could ask in replit official discord server.

jolly geyser
#

but i just want to know how to get my bot's token with python

#

i just want faster way

slate swan
#

Yeah, but this doesn't seem like a python problem.

jolly geyser
#

ik

dull terrace
#

i have a long string with guild names in which is split

#

so user input so whatever characters i split by better not be in a guild name

dull terrace
#

string is something like "guild_nameSPLITSTRINGscore"

#

so if someone changes their guild name to something like

#

sadfgsdSPLITSTRINGscore

#

try except wouldn't stop exploit

slate swan
#

Sorry, didn't understand your question

dull terrace
#

yeah thats why im asking

#

what characters are disallowed

#

the string is "guildname<my string>score"

#

fuck

tidal hawk
#

Why is it so that my bot slash commands doesn't appear on some servers

#

Like it doesn't show in 1/2 servers

bitter perch
#

do all of those servers have your bot with the application_commands scope

tidal hawk
#

Yeah I have like 15 total commands and 14 of tem are only showing ** in my server**, but in other servers all are being shown

dull terrace
#

Slash commands are finicky from what i hear, new ones take a while to show up sometimes

sick birch
#

They can take up to an hour yes

#

For global ones that is, guild specific ones are instant

tidal hawk
#

Yeah, it's just funny that it's in every other server, instead of mine xD

sick birch
#

If its global its probably just bad luck and you’ll have to give it some time to propagate fully

south jetty
#
    @commands.command()
    @commands.has_role("Middleman")
    async def rename(self, ctx):
        await ctx.channel.edit(name = )```
How can I make it so edit the channel name `-rename {new name}`
cold sonnet
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

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

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
junior verge
#

xD

river swift
#

GOOOOD

#

xDDD

cold sonnet
#

unlucky

hybrid mural
#

Hey so switching from discord.py to discord.py 2.0 got me some errors:

RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited
bot.add_cog(help_cog(bot))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Any fix? Don't really know why cogs have to be awaited now

cold sonnet
#

make the setup function an async function

#

and await the add_cog

hybrid mural
#

which setup function are you referring to? Hold on ill send the code

river swift
#

ÑÑÑÑÑ

hybrid mural
#

import discord
from discord.ext import commands

class help_cog(commands.Cog):
def init(self, bot):
self.bot = bot
self.help_message = """

Music Bot commands:
+help - displays all the available commands
+p <keywords> - finds the song on youtube and plays it in your current channel. Will resume playing the current song if it was paused
+q - displays the current music queue
+skip - skips the current song being played
+clear - Stops the music and clears the queue
+leave - Disconnected the bot from the voice channel
+pause - pauses the current song being played or resumes if already paused
+resume - resumes playing the current song
+loop - loops the current song
+isloop - checks if loop is active(True or False)
+lyrics - sends lyrics of the current song

General Bot commands:

+gif (whatever gif you want) - will get you the gif you search for if possible
+animals - will return a random Animal Picture and Fact

"""
self.text_channel_list = []

@commands.command(name="help", help="Displays all the available commands")
async def help(self, ctx):
    await ctx.send(self.help_message)
cold sonnet
#

there's a setup function under that cog

cold sonnet
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.
river swift
cold sonnet
#

!d discord.ext.commands.command

unkempt canyonBOT
#

@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") using utf-8 encoding.

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
cold sonnet
#

!d discord.ext.commands.Bot.command

unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
hybrid mural
cold sonnet
#

no

hybrid mural
cold sonnet
#

a setup function

#

show what you have under that cog

#

everybody uses a setup function under the cog

river swift
#

What library do you recommend me to install in replit?

hybrid mural
#

bot.remove_command('help')

bot.add_cog(help_cog(bot))
bot.add_cog(music_cog(bot))

@tasks.loop(minutes=10)
async def every_10_min():

cold sonnet
#
def setup(bot):
    bot.add_cog(Cog(bot))
```looks smth like this
hybrid mural
#

Ah so an extra setup function has to be added?

cold sonnet
#

it's what the docs teach you

#

and is the easiest

hybrid mural
cold sonnet
#

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

hybrid mural
#

ah ty ill try the setup function wasnt needed in the old discord.py

cold sonnet
#

still everybody used it 😦

river swift
#

What library do you recommend me to install in replit?

cold sonnet
#

replitn't

cold sonnet
#

make sure to put it in the cog file, being async and use bot.load_extension in main.py in some way

hybrid mural
#

Yeah it works now

#

Onto the next thing, I guess something changed with loops aswell? I have to await some kind of loop now

cold sonnet
#

when using bot.loop to play music, innit

hybrid mural
#

Nah its the kind of loop that sends something in a specific channel every 10 minutes

cold sonnet
#

oh tasks.loop

hybrid mural
#

yup that one

cold sonnet
#

¯_(ツ)_/¯

hybrid mural
#

ill send the error

cold sonnet
#

that would help both of us

river swift
cold sonnet
#

no

slate swan
cold sonnet
#

or just discord

slate swan
#

discord is just a mirror package for discord.py so yea that works too

river swift
hybrid mural
# cold sonnet that would help both of us
Traceback (most recent call last):
  File "C:\Users\damn\PycharmProjects\pys\main.py", line 185, in <module>
    every_10_min.start()
  File "C:\Users\damn\PycharmProjects\pys\venv\lib\site-packages\discord\ext\tasks\__init__.py", line 400, in start
    self._task = asyncio.create_task(self._loop(*args, **kwargs))
  File "C:\Users\leka\AppData\Local\Programs\Python\Python310\lib\asyncio\tasks.py", line 336, in create_task
    loop = events.get_running_loop()
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
hybrid mural
slate swan
river swift
slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:6: RuntimeWarning: coroutine 'a' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
slate swan
river swift
#

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

slate swan
#

!d discord.Embed

river swift
#

BRUHHH

unkempt canyonBOT
#

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

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

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

New in version 2.0.

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

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
slate swan
slate swan
hybrid mural
#

im sorry im transitioning from C# to python , whats a coro in that case?

#

coroutine i assume

slate swan
#

a coro/coroutine is an async function

#

at last

#

!code

echo wasp
#
    @commands.command(name='Leave')
    @commands.has_permissions(manage_guild=True)
    async def Leave(self,ctx):
        await ctx.channel.send("Very well, idk why you would want me to leave but ok bye")
        await asyncio.sleep(1)
        await ctx.guild.leave()``` I am wondering how to make it check if i run the command and if it isn't me running the command it checks for manage_guild
slate swan
#

!d asyncio.create_task

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
idle laurel
#

when im running a task loop how can i send a message direct to a user? usually i used ctx.author.send(embed=embed) but i dont have ctx in the function args

echo wasp
slate swan
slate swan
unkempt canyonBOT
#

@check```
A decorator that adds a global check to the bot.

A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.

Note

This function can either be a regular function or a coroutine.

Similar to a command [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").

Example...
idle laurel
idle laurel
#

sound cheers

slate swan
hybrid mural
#

i assume i have to call the async function with await every time

slate swan
#

needs to be a member or user obj

slate swan
#

pfftt uploading on pypi for the first time is a hell of work 😔

hybrid mural
#

so now because i cant await outside a function i have to do an async setup function

slate swan
idle laurel
# slate swan no, since, that is an integer

im storing the users id in a database linking it with other info, if the criteria is met for that person im trying to send them a private dm. whats the best way? im a little confused

slate swan
echo wasp
slate swan
slate swan
slate swan
hybrid mural
slate swan
# slate swan AHHH you need an init file

no xD, when I did pip install I wanted from DscPyDB import LevelDB but it came out to be from db import level_db because I mentioned paths wrong but fixed it eventually, now it works peephappy

#

how do i have a bot discord system ?

slate swan
spring cape
#

Can I disable message reaction permissions with discord.py?

river swift
#

How do I start making a bot in visual studio code?

slate swan
slate swan
slate swan
slate swan
cold sonnet
#

def not cuz of youtube

slate swan
slate swan
slate swan
slate swan
slate swan
slate swan
echo wasp
slate swan
#

damn you should be a comedian no joke

slate swan
slate swan
#

and i have no jobrooThink

#

meh kek

#

@slate swan it's not your job bro wtf

#

you asked what is my job i have no job

spring flax
#

anyone knows the black formatter for code?

unkempt canyonBOT
#

src/DscPyDB/db/economy_db.py lines 5 to 8

class EconomyDB:
    def __init__(self):
        self.CollectionTuple = namedtuple('Column', ['id', 'wallet', 'bank'])
        asyncio.run(self.init_db())```
slate swan
#

@slate swani didn't asked you

#

shit

#

it's not your job

#

we dont talk about it

hybrid mural
#

bro

slate swan
#

bro this guy is giving me a stroke

hybrid mural
#

xd

slate swan
slate swan
#

a class method can be a coroutine

#

@slate swandiha fkrk azbi mal tbon mk b9a 7adini

spring flax
slate swan
echo wasp
#
    @commands.command(name='Leave')
    @commands.has_permissions(manage_guild=True)
    async def Leave(self,ctx):
        await ctx.channel.send("Very well, idk why you would want me to leave but ok bye")
        await asyncio.sleep(1)
        await ctx.guild.leave()``` I am wondering how to make it check if i run the command and if it isn't me running the command it checks for manage_guild
slate swan
#

@slate swan shit this fuck up fuck you and ur mom wtf @slate swan

spark sentinel
#

Hello, can someone recommend me something for an invite logger?
for pycord

hybrid mural
#

Does anyone know how i can format Buttons which im gonna send?

spring flax
slate swan
#

@cold sonnet okey sorry

#

this guy have mee hemshakehemshake

cold sonnet
#

mod's coming

cold sonnet
slate swan
spring flax
#

yesh

smoky anvil
#

Someone who can help, how to do a giveaway bot with invite require ment?

echo wasp
#

@slate swan may i have the correct docs to look at to make my custom check?

unkempt canyonBOT
#

src/DscPyDB/db/economy_db.py lines 35 to 42

async def create_account_if_not_exists(self, user_id: int, wallet_amount: int, bank_amount: int):
    res = await self.read_data(user_id)
    if not res:
        await self.execute_and_close("INSERT INTO users(id, wallet, bank) VALUES(?, ?, ?)", (user_id, wallet_amount, bank_amount,))
        return self.CollectionTuple(user_id, wallet_amount, bank_amount)
    return self.CollectionTuple(res[0], res[1], res[2])

async def update_account(self, user_id: int, *,wallet_amount: int=None, bank_amount: int=None) -> bool:```
spark sentinel
#

Hello, can someone recommend me something for an invite logger?
for pycord

slate swan
spring flax
unkempt canyonBOT
#

@discord.ext.commands.check_any(*checks)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if any of the checks passed will pass, i.e. using logical OR.

If all checks fail then [`CheckAnyFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckAnyFailure "discord.ext.commands.CheckAnyFailure") is raised to signal the failure. It inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Note

The `predicate` attribute for this function **is** a coroutine.

New in version 1.3.
quaint scaffold
# spark sentinel Hello, can someone recommend me something for an invite logger? for pycord

get current invites, store

on member join:
get and store new invites
check invites to see if one has incremented
if one has, that's your invite, return

else:
    if an invite is missing, it might be it was a limited use one or expired- add it to a list of things to return
    check vanity invite to see if it incremented
         if it did, return that
    poll audit log to see if any invites were created recently
         if one was, add that to things to return, return

else mystery

hybrid mural
#

Is it possible to get multiple interactions from Buttons in a single message?

spark sentinel
austere herald
#

Hey, I'm a little bit curious

#

How would I do a wait_for event for voice?

quaint scaffold
austere herald
#

I want something a little like this

echo wasp
hybrid mural
#

And is it possible to format Buttons in a specific way lets say... TIC TAC TOE? (and send it ofcrs)

austere herald
#

I'm on the latest discord.py 2.0 with app_commands, having switched from a fork

slate swan
spring flax
hybrid mural
slate swan
hybrid mural
#

br

slate swan
spring cape
#

Does anyone know if there is a payload.member alternative but for ctx?

slate swan
spring cape
spring flax
# echo wasp yes

@commands.check_any(commands.is_owner(), commands.has_guild_permissions(manage_guild=True)

slate swan
spring flax
#

@slate swan have you got anything on the black formatter?

hybrid mural
slate swan
slate swan
echo wasp
slate swan
slate swan
slate swan
#

sure

#

its a good idea you just need to fix some stuff

spring flax
unkempt canyonBOT
#

@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/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/master/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/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
slate swan
hybrid mural
#

@slate swan excuse me ill try to understand the whole code so i can atleast learn from it, what does ```py
super().init(style=discord.ButtonStyle.secondary, label='\u200b', row=y)


mean exactly
echo wasp
slate swan
hybrid mural
#

I see the super(). thingy the first time

slate swan
spring flax
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
slate swan
hybrid mural
#

Oh ok ty

slate swan
echo wasp
spring flax
spring flax
echo wasp
#

lol i do

slate swan
idle laurel
#

How can i send a embed privately with knowing the user id inside a task? usually im doing ctx.send but ive not got ctx in the args able to use

slate swan
cloud dawn
#

Super is kinda like coding in creative mode

hybrid mural
#

@slate swan is this TicTacToe you sent me really the easiest ? Wouldnt it be easier to just send the buttons formatted and if the top left button gets pressed it gets changed to an X or O button depending on what player it is while after the button has been clicked theres a function that checks if theres a win or tie on any player side?

#

Thats atleast how i imagined i'd code it

slate swan
slate swan
slate swan
hybrid mural
#

Well the only thing im stuck on is the formatting after i have that i'd probably be able to do it

slate swan
#

formatting like?

spring flax
#

after --code

hybrid mural
#

Lets say blank Buttons Formatted to this:

🔳 🔳 🔳
🔳 🔳 🔳
🔳 🔳 🔳

basically

slate swan
hybrid mural
#

and then theres the problem with ctx.send(components) you cant really have more than 5 buttons in a message i think

slate swan
#

nah its 26 iirc

hybrid mural
#

ignoring the fact you cant add rows to it

hybrid mural
manic wing
hybrid mural
#

But then adding the buttons to the components i cant really format it in any way

manic wing
spring flax
slate swan
quick gust
spring flax
pliant gulch
#

python without a dash

#

Make sure it's installed

#

Black that is, ^

spring flax
#

yeah did pip install black

quick gust
pliant gulch
#

Ok, then python -m black ./ should work fine

velvet compass
#

Also give it a file or directory to run on. Like black . to run on the current directory, or black test.py to only do that file

#

(also a bit off topic for this channel, sorry about that)

spring flax
pliant gulch
#

If your following a specific guideline that sets line length, you can also set the --line-length flag

manic wing
spring flax
#

i want to do ;format [code] and it formats it

velvet compass
#

Oh, I missed the context

spring flax
#

i'm not completely familiar with this but would stringIO work?

echo wasp
#

How to make a good help command that is not hard coded?

pliant gulch
#

Just call black with the -c flag

#

python -m black -c "code here"

spring flax
pliant gulch
#

Oh ok

spring flax
#

it's the same right?

crisp cape
#

new to the server so forgive me if this isn't quite on topic but google has failed me.

I understand you can connect your github account to your discord account. Is there some form of automation that exists that will give a discord user a role if their github account is connected to their discord account?

pliant gulch
#

Yep, --code is just the human readable

manic wing
#

you know that f-string does nothing right?

spring flax
#

it raises ```Usage: python -m black [OPTIONS] SRC ...
Try 'python -m black -h' for help.

Error: Invalid value for 'SRC ...': Path '=' does not exist.```

hybrid mural
#

ahh @slate swan i found a fix i didnt know discord.ui.buttons now had a "row=" parameter which helps identify

echo wasp
#

how to make a help command that is not hard coded???

spring flax
slate swan
#

didnt dpy end?

halcyon sparrow
#

It was recuntinued a while ago

jade jolt
#

When?

slate swan
#

how do i implement slash commands?

halcyon sparrow
#

Checkout the links in the channel description

hybrid mural
#

Did dpy 2.0 change something about components? I cant add components anymore:

TypeError: Messageable.send() got an unexpected keyword argument 'components'
junior verge
#

What perms would be good enough for a giveaway like how high

slate swan
slate swan
#

Hm?

slate swan
slate swan
#

dpy

slate swan
#

How do I get 2.0

#

pip install -U git+https://github.com/Rapptz/discord.py

hybrid mural
#

is there somewhere i can look up view on ?

south jetty
slate swan
south jetty
slate swan
#

Explain that agian please

south jetty
south jetty
slate swan
#

Do ctx, *, new_name

#

The * makes it able to have multiple words.

south jetty
#

oh

hybrid mural
#
Command raised an exception: TypeError: expected Item not <class 'function'>
``` Wut Wrong
#

i get it

#

i need to use

#

discord.ui.Item add the button as an item and then

slate swan
#

Wasn't that what you did?

hybrid mural
#

Yeah but the item= only takes "Item" type an button itself isnt an Item Type

#

i need to first cast the button to an Item

hoary cargo
#

maybe just try to add buttons one at the time, why do you even need 2 loops to add items

hybrid mural
#

ive got 3 rows of 3 elements[list] (referring to tictactoe) each element representing a button

#

id rather not manually type out all the buttons there are

slate swan
slate swan
#

What do forks do? I heard about pycord a lot

#

I am used to the basic orignal dpy

#

do I have to change the entirity of my code?

slate swan
slate swan
slate swan
#

What's the error?

slate swan
#

Done, it installed.

#

Yes

#

How do I do slash commands? like implement them to my commands

slate swan
#

Uninstall the discord app?

slate swan
#

Done

#

I don't think that works

slate swan
#

from discord.commands import slash_command <--- that has a yellow line under it

#

should I be worried?

#

Nah

slate swan
#

I heard slash commands could do that

#

Sten, I have an error.

No module named slash_commands

#

I apologize,

no module named discord.commands

#

Well then you haven't install pycord properly.

#

What do you want to use? Discord.py, pycord, nextcord?

#

All three have it

#

import nextcord

#

Personally I think pycord

#

Don't import discord

slate swan
#

should I do that?

slate swan
#

You choose

#

For pycord, just do import discord.

#

I have done everything as said, why is it not working? oh and it says in the problems tab that

import "discord.commands" could not be resolved pylance(ReportMissingImports) [3,6]

#

What's your code?

slate swan
slate swan
#
import discord
from discord.ext import commands
from discord.commands import slash_command```
#

You have to uninstall discord and install pycord.

#

How can i make my discord bot send a list of text? such as

  1. sub to my youtube
  2. follow my tiktok
  3. follow my instagram?
slate swan
slate swan
#

alright looks good thanks

slate swan
#

What IDE?

manic wing
#

discord bots is a beginner friendly place :)

slate swan
#

👍

#

Like vscode, pycharm.

#

sten checkout my screenshot

slate swan
#

Why can't I install it?

unkempt canyonBOT
#

Hey @slate swan!

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

slate swan
#

How do I stop that from happening

slate swan
#

vscode

#

Maybe you should use disnake instead.

#

Alright, how do I do that

#

Both

#

Yes

slim ibex
#

pip3 install disnake

slate swan
#

done

#

import disnake has a yellow line under it

slate swan
slate swan
slate swan
slate swan
#

like disnake.User

slim ibex
slate swan
slate swan
slate swan
slim ibex
#

you have disnake.commandsthat isn’t a valid thing

slate swan
#

Doesn't disnake have it's documentation here?

#

like this?

slim ibex
#

you can’t get docs for the whole mf extensions command LOL

slim ibex
#

and remove discord import

slate swan
#

okay

#

now almost every command has a yellow line under it

#

also these

#

and when i run the bot it says no module named disnake

slim ibex
#

replace all discord with disnake

#

and do you have disnake installed/right interpreter selected

slate swan
#

Or just import disnake as discord

slim ibex
#

no pls no

slate swan
slate swan
slate swan
slate swan
#

already satisfied

stone beacon
#

🗿

slate swan
#

im using python 3.9, is that okay?

#

Yes

hybrid mural
#

How would you get the Interaction of a button now in dyp 2.0?

slim ibex
#

💀

slate swan
#

I hate this documentation feature

slim ibex
#

!d disnake.Interaction

unkempt canyonBOT
#

class disnake.Interaction```
A base class representing a user-initiated Discord interaction.

An interaction happens when a user performs an action that the client needs to be notified of. Current examples are application commands and components.

New in version 2.0.
slate swan
#

!d disnake.ui.Button

unkempt canyonBOT
#

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

New in version 2.0.
hybrid mural
#

disnake?

slate swan
sick birch
slate swan
#

Wha

sick birch
slate swan
#

!d discord.ui.Button

unkempt canyonBOT
#

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

New in version 2.0.
slate swan
#

Meh

sick birch
#

slash commands, buttons, etc

slate swan
#

!d discord.SelectOption

unkempt canyonBOT
#

class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.

These can be created by users.

New in version 2.0.
slate swan
#

That's what I meant

hybrid mural
vale wing
#

Change "stable" to "master" in url

slate swan
hybrid mural
hybrid mural
#

ty : )

sick birch
round robin
#

does anyone know a fix to this? its still broken https://p.andyishereboi.com/suyinamuxa
mycursor.execute(f"SELECT * FROM `count` where `id` = `{self.guild_id}`") NameError: name 'self' is not defined

cold sonnet
#

!resources

unkempt canyonBOT
#
Resources

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

round robin
#

meh

cold sonnet
#

learning oop will quite help

#

also, why are you playing minecraft since a day ago

round robin
#

its open a computer at my school

#

they didnt shut it down over the weekend

#

so now its ganna be 3 days

glass dock
#

Help! How to create a thread in pycord?

slate swan
#

can anyone help me with this error im getting/

round robin
#

i see self there as a argument so idk

minor totem
#

If you look at the code, what do you want to happen and when?

round robin
#

i want it to be able to get the guild id of a view before its added to the message

slate swan
#

anyone know what is wrong?

round robin
#

there is no ctx.channel.send

#

its just ctx.send

minor totem
slate swan
#

can that be the reason?

hybrid mural
#

What Button command do i have to put in discord.InteractionType() so it registers a button got clicked

slate swan
minor totem
# slate swan

Can you please format your code to be readable? I can't read that

round robin
#

well i see no error

minor totem
round robin
#

yes

slate swan
minor totem
# round robin yes

Python is now complaining that it isn't defined, do you think it's (self) defined?

round robin
#

isnt self just something that u have to put into classes

#

idk how to use it really

#

i watched a full video on it and i still dont get it

slate swan
glass dock
#

How to create a thread in pycord?

round robin
minor totem
glass dock
slate swan
#

Oh wait, it might be that i made a class the same name with the file im importing

minor totem
round robin
#

1 google search is all it takes

minor totem
# slate swan

You don't need to keep sending the screenshots again, and again. Is this pycord?

minor totem
round robin
#

i was just saying that searching for it would be quicker then asking here and it saves everyone time

glass dock
#

Yes, but it doesn't work. No error

minor totem
slate swan
minor totem
minor totem
minor totem
glass dock
#

I do not know why

slate swan
glass dock
#

i try await ctx.message.create_public_thread('Thread', auto_archive_duration = 3600)

cold sonnet
#

I see you have registered a function as an event and command?

slate swan
#

^^ This is temporary im trying to learn discord.py.

#

In the feature i will be using MySQL.

cold sonnet
#

okay, and what's app()?

minor totem
# minor totem Ok

@glass dock you responded with a statement, just "it didn't work", at which point my response was "Ok'". I am not trying to carry the whole conversation, you can continue the conversation by asking another question, which I can respond to. As always, explain your problem and I'll explain the answer.

minor totem
glass dock
#

nope

slate swan
cold sonnet
#

okay, well, you don't need that to define a command

minor totem
# glass dock nope

So- you run this, and it runs the code, but no thread is created? Add prints before and after the line of code, so that you know that it worked!

slate swan
#

!status

#

i need the self.client to.

cold sonnet
#

and the Commands class should be a cog I guess?

glass dock
slate swan
#

I'm storing the actual commands in other files.

glass dock
#

No error and action

slate swan
#

to make it look cleaner.

minor totem
# slate swan

I think I get it now! Your decorators are in the wrong order.

glass dock
cold sonnet
#

actually, you define commands as @commands.command() in a cog

#

and you have to subclass commands.Cog, not just make a class

hybrid mural
#
        interaction = discord.Interaction(type=discord.ComponentType(discord.Button(data=discord.ui.Button)))

Im trying to catch a Button Interaction i just dont know what the syntax for discord.Interaction is ive read docs im lost though

minor totem
#
try:
    ...
except Exception as e:
    print('ran into', repr(e))
minor totem
hybrid mural
#

yeah

#

basically i send buttons,
user clicks one,
then i catch the Interaction

minor totem
#

Do you not want to use views?

hybrid mural
#

i did use views

minor totem
#

Then you should have the interaction inside of the button callbacks

glass dock
hybrid mural
minor totem
cold sonnet
#

kekw

glass dock
#

Yes, but ...

#

I seem to have done everything right.

minor totem
cold sonnet
#

nothing

minor totem
slate swan
#

how do i add a status to my discord bot?

minor totem
slate swan
hybrid mural
glass dock
# slate swan how do i add a status to my discord bot?
# Setting `Playing ` status
await bot.change_presence(activity=discord.Game(name="a game"))

# Setting `Streaming ` status
await bot.change_presence(activity=discord.Streaming(name="My Stream", url=my_twitch_url))

# Setting `Listening ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a song"))

# Setting `Watching ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="a movie"))   
minor totem
hybrid mural
cold sonnet
# slate swan to make it look cleaner.

okay, you don't look like someone who doesn't know about classes

  1. subclass commands.Cog
  2. save your bot to self.bot
  3. make a command
  4. setup function
class Test(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
    #here, you define commands as @commands.command()
    @commands.command()
    async def test(self, ctx): #don't forget self
        await ctx.send("test")

async def setup(bot):
    await bot.add_cog(Test(bot))
glass dock
#

sorry if i'm doing something wrong

minor totem
hybrid mural
#

basically yeah

glass dock
#

😅

hybrid mural
#

and change it then but that comes after knowing which one got pressed

minor totem
cold sonnet
#

but there's a documentation about cogs in the api reference

glass dock
slate swan
#

It wasn't about classes, it was how i ordered the client.command and @client.event

cold sonnet
#

what

outer parcel
#

does anyone have a quick name idea for discord bot please

minor totem
cold sonnet
#

bluenix called it and it just doesn't make sense to have an eventcommand for me

slate swan
hybrid mural
glass dock
# slate swan

Perhaps you wanted to do py from discord.ext.commands import Bot
?

cold sonnet
#

that's unnecessary memory usage...

outer parcel
#

anyone please discord bot name

slate swan
#

One more question how do i get a users ID?

glass dock
minor totem
# glass dock `*` ignores spaces in the argument if I'm not mistaken

That's what discord.py uses them for, but they have a different usage in Python. It means keyword-only parameters.

Keyword-only parameters means that when you call the function, you have to specify the parameters by name: ```python
def add(*, a, b):
return a + b

add(1, 2) # Will fail!
add(1, b=2) # Will fail!
add(a=1, b=2) # Will fail!

In your case, you tried to pass the name without doing `name=`. Whenever you read `*` like that, it means that all parameters (the variables with the commas) after it have to be used like this.
minor totem
# cold sonnet what

What happened was that a command was first created and returned instead of the function, then this command was passed to @client.event. By switching the order, first the event is registered and the coroutine is returned untouched, then the command is created.

minor totem
minor totem
cold sonnet
slate swan
minor totem
minor totem
cold sonnet
#

but only specified named events are called 😳

minor totem
hybrid mural
#

shouldnt you get the button_id anyway?

#

i mean the custom_id from the buttons

minor totem
hybrid mural
#

true

#

then what does Interaction return after a button gets clicked

#

better to say is how would i be able to find out what button was clicked with Interaction*

minor totem
#
view = View()

interaction = None
button = None
has_called = False

def create_callback(name):
    async def callback(inter):
        if has_called:
            # If a button has already been called, ignore it
            return

        nonlocal interaction, button, has_called
        interaction = inter
        button = name
        has_called = True
        view.stop()
    return callback

# Now add items with this callback, replace ... with the name you want to use (probably same as custom_id)
discord.ui.Button(label="\u200b", row=i, custom_id=("button" + str(i) + "," + str(j)), callback=create_callback(...))


if await view.wait():
    # The view timed out, meaning that no button was pressed. Handle this somehow

# interaction, button should now be defined to the name you gave the button and interaction it was called with
#

You could use something like this, as you can tell it's kinda advanced. The class way of doing it would be very verbose though

#

Since you'd need to repeat the same code for each button. You're sadly working against discord.py, these are the only options I can come up with.

#

Not a huge fan of the view system all the time, it has its charms but sometimes you just want something lowlevel.

hybrid mural
#

yeah true