#discord-bots
1 messages · Page 931 of 1
If you go work for someone and you produce code using your methodology I guarantee they won't like you
Useless argument?
Well the first one could be really hard if there's just a lot of variables and math. Better to make it easy.
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
they wont like you either if you over do everything.
"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/...
Not useless but outside the scope of this channel
Nah its related to syntax
I think we should stick with the channel's theme here, it's getting out of hand xd
Alright
- 1
im not sure why you guys call this an "argument" when we are having a civilized conversation
except replit with uptimerobot
That's not a hosting service
im porr
Aws free trial
if u use keep alive, then yes its a hosting service
AWS might do I guess
i tried heroku, but a weird issue
Nah, it just pings your repl, that's not a hosting service.
epik host is gone
it keeps the bot alive 24/7
Lol
keep alive isnt even for hosting its used to keep a connection alive
wut
Sure, but it isn't a hosting service.
nvm
I didnt print..
can anyone give?
What
?
Self hosting is free tho
but it aint 24/7
Overreacted
rpi is good as well
It can be, just don't shut your computer down
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)```
!paste
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.
the bottom lines is my ban cmnds, they dont work for some reason
Aws free trial
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
👀
hes just being polite whats wrong with that
i dont have credit card
Many possibilities
what what
Why eyes
why not?
im not sure why you guys are overreacting over someone who i helped is grateful?
why is it weird?
it isnt ;-;
Check ur bot perms
Firstly you don't know difference between client and Bot, and for your issue your on_message event isn't processing commands
sorry
Add await client.process_commands(message)
i stopped reviewing the code when i saw format and f strings in the same snippet
where in the code @slate swan
listen!
!d discord.ext.commands.Bot.listen
@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...
It was a client.event he had
You still pay for electricity lol
Wah here we go again
im so new to python idk what you mean man

isn't that a felony?

Because it totally makes sense to commit a crime just to host a discord bot
Make a server of some old computer parts, install ubuntu on it and enjoy
Personally I am gonna do that when I get time
😏
Or just buy a raspberry pi
Rule 5 screams in pain
Why buy something when you already have
Why not have more
Power
Raspberry Pi and your own server costs more in the end compared to a cheap monthly VPS, but regardless they are fun projects
Takes space
Btw most people just give up on discord bot coding later so I don't it is a good idea to invest.
That thing about the rule was a joke no need to delete it haha
I don't want to get banned 🤷♂️
wdym?
People barely monetize them
pretty good idea, i have a netbook lying around, might get that started up
I could have done that if stripe wasn't banned in Russia
Most people do it for fun and it's a pretty good learning method
Yes
I started learning dbs because of my bot xd
It isn't, as far as my experience is concerned
I don't mean it for beginners but it's a good way of giving a good use to the things you learn
I am now like at level of PCPP-1
I made the same mistake so ik that
It worked great for me when attempting to learn asyncio bases
What worked great
Learning python with discord.py
That's not good
Especially beginners
what's the attribute for give role?
For beginners it won't work at all lmao
.
Erm do you mean how to add role?
yea
!d discord.Member.add_roles
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.
what is atomic?
Always wondered what atomic param does
Ig when it's true all roles are added within one API call
Atomic bomb dunno
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?
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
Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.
is permission.value the value of permission int?
context = "your text"
Atomic operations are just operations that run independent of any other processes
u use this for what ?
This is a more general programming term, not specific to discord.py
Either you didn't add self Param in a command in a cog or you missed ctx outside the cog
that's what I meant
ok
thx
Oh thx finally someone explained it in a normal way
You learn most of this basic stuff in computer science or something
i see ill check
!d discord.Ember.colour
It's the same
thats not the error though
Srry but I was a bio student...
I am a self learner so uh I might not know something that is given in standard learning programs
well it is, the attribute name is colour not color
embed.color = ...
dosen`t exist
embed = discord.Embed(description = "text", color=0x2f3235)
But I have somewhat of a vast background in computer science
I am literally a musician k
I just started from biology and planning to become a biomedical engineer
!d discord.Embed
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`.
i mean it sent the embed how i wanted it to be soo
but that isnt whats causing the error isnt it
It is better to provide description and color in the constructor
Nice, you’d benefit from learning some immunology
hi, from where can i learn discord.py?
It should be because you have same var for your view and your command
This is a good tutorial https://vcokltfre.dev
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
After you finish it you can just explore through docs when you need something
async def role(ctx):
view = role()
Ah yes
oh
Nice recursion
i see lemme change that rq
it is indeed, thank you so much
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
that event fires once a member joins
maybe a member doesnt join
is the bot also in the same server?
yeah
is there a way i can get my discord bot to message a user privatly when a criteria is met inside a database?
use tasks
to see if criteria is met
its in discord.ext
import from here and use it like
yes
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
@tasks.loop(seconds=60)
async def blabla():
...
blabla.start()
any idea?
try async def on_member_join():
no different like, but im using the same func and it works fine thats weird
sorry can someone send the docs on renaming channels
cant seem to find it
on member join needs an argument
!d discord.TextChannel.edit
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...
can someone teach me how to see python API
What python API?
!d discord.ext.commands.Context.message returns a Message object
The message that triggered the command being executed.
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.
not with ctx
You said command message
a command is ctx
it says, that ctx has no attribute "delete"
I tried ctx.delete()
Yeah you don't do that
You need a message object
my on_member_join event doesnt work guys, I didnt understand why
!intents
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.
the same way you'd do in python
got it
nice
nah
.
?
😔
It's technically the truth
Is it possible in dpy to have a command name like 8ball in cogs with a number like 8ball
yes
How?
just create the command as you would do for any other
@commands.command(name='8ball')
async def roll(foo, bar):```
How to make a snake game on python?
you can't name your function 8ball because python functions must start with a letter or an underscore
what is the second part of discord bot token?
nad amas
Not in the aliases too?
first one is utf 8
but what is second
context has the message attr which returns a message object so just do await ctx.message.delete()
not related to discord-bots
since the aliases are strings, it's fine for them to be whatever
so that can be 8ball?
what?
Ok ty
discord bot token
as long as it's py aliases=['8ball'] sure
utf-8 is encoding for text files, i don't know what you're talking about
lol now i realized that question is your
Lol
discord token have utf 8 code and what is second part of token code?
no, the first part of the discord token is the ID of the application or user encoded to base64
the second part is an unix epoch used for tokens, also encoded to base64
thank you
and the third part is HMAC, the cryptographic key that is actually used for authentication
is it possible to encode whole token?
wdym
in python
yes, you can use python to encode/decode strings
but i don't know why you would want to do that
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
You only need it once
^
yes i know but that token resets almost every time
idk why
no it doesn't
it does now, no?
nah i have one issue with my pc
It only resets when you press the reset button.
the token for a bot application?
yes i know but i have one issue
And it is?
the only discord tokens that reset themselves are used in user authentication
which kind of makes this case suspicious
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
no, you can always copy it again
Well that is true
Nah
then they changed it in the one month i've been away from pydis
i coded my bot but every day it tells me that token does not exist then i go to the devolper portal and i see that reseted
I changed like two weeks ago I think
but i don't want to go to the devolper portal every time
yeah, i see
it is indeed like that now
still, it shouldn't magically reset on it's own
The bot token still doesn't reset by itself.
Can you show us the message?
it says like smth like error: repl.it cant find bots TOKEN. please try to add token again or regenerate it
that's weird
if that's the case, you've gotten a warning each time you pushed to github
replit is almost same as github
so you've been ignoring it
bru
literally nothing like each other
Do you have it in like a .env?
yea
then how are you reading the token from the env?
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
try running it from an IDE
and they're automatically encrypted, and loaded in each container
my mom doesn't allow me github idk why

I dunno what to say, anyways try running the code from an IDE
ok
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!
He doesn't have one
yea
Yeah, but then he said replit and replit doesn't support that.
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
That works too
If that's true, you might want to contact discord support.
my mom does not allow me that
._.
Well, you do have a quite big problem.
13
anyone know what characters are disallowed in guild names?
idk sorry
You could ask in replit official discord server.
but i just want to know how to get my bot's token with python
i just want faster way
Yeah, but this doesn't seem like a python problem.
ik
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
Hm?
string is something like "guild_nameSPLITSTRINGscore"
so if someone changes their guild name to something like
sadfgsdSPLITSTRINGscore
try except wouldn't stop exploit
Sorry, didn't understand your question
yeah thats why im asking
what characters are disallowed
the string is "guildname<my string>score"
fuck
Why is it so that my bot slash commands doesn't appear on some servers
Like it doesn't show in 1/2 servers
do all of those servers have your bot with the application_commands scope
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
Slash commands are finicky from what i hear, new ones take a while to show up sometimes
They can take up to an hour yes
For global ones that is, guild specific ones are instant
Yeah, it's just funny that it's in every other server, instead of mine xD
If its global its probably just bad luck and you’ll have to give it some time to propagate fully
Okay
@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}`
!d discord.Embed
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`.
xD
unlucky
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
which setup function are you referring to? Hold on ill send the code
ÑÑÑÑÑ
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)
there's a setup function under that cog
!d discord.ext.commands.Command
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.
thx
!d discord.ext.commands.command
@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.
!d discord.ext.commands.Bot.command
@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").
where's your bot.add_cog?
you mean the def init
no
a setup function
show what you have under that cog
everybody uses a setup function under the cog
What library do you recommend me to install in replit?
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():
def setup(bot):
bot.add_cog(Cog(bot))
```looks smth like this
Ah so an extra setup function has to be added?
Also how do you put messages in this type of format
!code
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.
ah ty ill try the setup function wasnt needed in the old discord.py
still everybody used it 😦
What library do you recommend me to install in replit?
replitn't
though this is the stable version of dpy setup function
make sure to put it in the cog file, being async and use bot.load_extension in main.py in some way
Yeah it works now
Onto the next thing, I guess something changed with loops aswell? I have to await some kind of loop now
when using bot.loop to play music, innit
Nah its the kind of loop that sends something in a specific channel every 10 minutes
oh tasks.loop
yup that one
¯_(ツ)_/¯
ill send the error
that would help both of us
?
no
or just discord
discord is just a mirror package for discord.py so yea that works too
oh
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
await the coro
i think this might install the old version of discord.py
sup
!e
import asyncio
async def a():
...
async def b():
a()
asyncio.run(b())
@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
hayo 
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.
!d discord.Embed
BRUHHH
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`.
await the coro oki
example on the error
nice
im sorry im transitioning from C# to python , whats a coro in that case?
coroutine i assume
a coro/coroutine is an async function
at last

@hybrid mural heres more info https://docs.python.org/3/library/asyncio-task.html
!code
@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
!d asyncio.create_task
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...
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
make a custom check
explain or docs?
you need to fetch/get the user and use the send method
!d discord.ext.commands.Bot.check
@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...
if ive got the user id in a "user" variable can i just do user.send
sound cheers
no, since, that is an integer
i assume i have to call the async function with await every time
needs to be a member or user obj
that is so
right
pfftt uploading on pypi for the first time is a hell of work 😔
so now because i cant await outside a function i have to do an async setup function
lol, I got import errors cz I specified my paths wrong 
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
new setup function in 2.0 is async fyi
relative imports
may i see an example for my senario?
no the one you do after installing the package
wait i gaved you wrong docs oops
AHHH you need an init file
what do you mean?
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 
how do i have a bot discord system ?
what....

Can I disable message reaction permissions with discord.py?
How do I start making a bot in visual studio code?
how can i have a bot discord system
A lot of people ask for economy bots and use json instead, so I made a helper package which uses aiosqlite with some functions to interact easily 
src
guess why
what is that
its a mess pfftt
def not cuz of youtube
idk
let me see
i need bot discord systemmmmm
what is that
repo?
yes wait
...
what did you say i need bot discord what is your job you
i had a stroke
and i have no job
meh 
@slate swan it's not your job bro wtf
you asked what is my job i have no job

anyone knows the black formatter for code?
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())```
bro
bro this guy is giving me a stroke
xd

use a classmethod
a class method can be a coroutine
@slate swandiha fkrk azbi mal tbon mk b9a 7adini
ew camelcase var
this got flooded super quick
I know, I just noticed
will fix it tomorrow, gtg rn
@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
what about black?
@slate swan shit this fuck up fuck you and ur mom wtf @slate swan
Hello, can someone recommend me something for an invite logger?
for pycord
Does anyone know how i can format Buttons which im gonna send?
can you please stop

do you know if a bot can format code inputted?
mod's coming
I feel it
well im not quite sure are you trying to format code to black for a command?
yesh
Someone who can help, how to do a giveaway bot with invite require ment?
@slate swan may i have the correct docs to look at to make my custom check?
let me check i kinda forgot it
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:```
Hello, can someone recommend me something for an invite logger?
for pycord
return annotations for one method and the other no?
!d discord.ext.commands.check_any
@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.
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 
Is it possible to get multiple interactions from Buttons in a single message?
uhm okay thx haha i try i try
yes
Yes as long as the view is not stopped.
I want something a little like this
may i have an example to check if the person running the command is myself if not has manage_guild perms?
And is it possible to format Buttons in a specific way lets say... TIC TAC TOE? (and send it ofcrs)
I'm on the latest discord.py 2.0 with app_commands, having switched from a fork
just subclass view and make the components
you mean if the user invoking the command either is you or has manage guild, it'll work?
Interesting can i have a read up on that?
br
pfftt, this is the least of my worries I swear I forgot about asyncio.run before I published
Does anyone know if there is a payload.member alternative but for ctx?
ctx.author ?
and you should make base exceptions if youre gonna raise them so you wont raise Exception but a base exception
yes
I'll try it, thanks!
@commands.check_any(commands.is_owner(), commands.has_guild_permissions(manage_guild=True)
just tell me if anything else is wrong, will fix it tomorrow ASAP
@slate swan have you got anything on the black formatter?
thank you dearly kind sir this will help me perfectly
oh ill make a whole txt file for you
im gonna check black docs give me a sec
may i see the docs for commands.is_owner()?
dw ill just delete the package tomorrow :)
my pleasure
let me contribute to it atleast
sure
its a good idea you just need to fix some stuff
!d discord.ext.commands.is_owner
@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").
@spring flax maybe this can help https://black.readthedocs.io/en/stable/usage_and_configuration/the_basics.html#as-a-string
@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
and where do i define my id?
f-fix them and make a pr pleeeeaaaaseee 
I see the super(). thingy the first time
you just make the code a string and it formats it and you just return the new ver of code
ok
tysm
commands.Bot has an owner_id kwarg, which takes in an int.
!d discord.ext.commands.Bot
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.
super() creates a instance of the parent class and it accesses any method from it or attrs
Oh ok ty
in this case it accesses the parents class initiate
this thing ```py
client = commands.Bot(command_prefix='%', intents=intents, owner_id=786788350160797706, Help_command=None, case_insensitive=True)
I can't find anything but i did see this there
Does Black have an API?
Not yet. Black is fundamentally a command line tool. Many integrations are provided, but a Python interface is not one of them. A simple API is being planned though.
it's help_command, not Help_command. And also I suggest changing the variable client to bot.
lol i do
how did you not found anything there? you can just run a command with os and make it format the string ver of the snippet
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
can you give an example?
let me make one give me a sec
Super is kinda like coding in creative mode
@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
__import__("os").system(f"black --code {'print ("hello world")'}")
something like this ig
well its just an example so i doubt it idk
its like being in creative mode and opening your inventory in mc
Well the only thing im stuck on is the formatting after i have that i'd probably be able to do it
formatting like?
what is that syntax?
after --code
Lets say blank Buttons Formatted to this:
🔳 🔳 🔳
🔳 🔳 🔳
🔳 🔳 🔳
basically
ah its just the command you are gonna add which the way black does it is black --code # code goes here
and then theres the problem with ctx.send(components) you cant really have more than 5 buttons in a message i think
nah its 26 iirc
ignoring the fact you cant add rows to it
oh ok thats an upgrade
25
But then adding the buttons to the components i cant really format it in any way
invalid syntax
operable program or batch file.
mhm
i didnt read full convo but try -python -m black
'-python' is not recognized as an internal or external command,
operable program or batch file.
yeah did pip install black
yeah that mb
Ok, then python -m black ./ should work fine
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)
for a command i want it to format
If your following a specific guideline that sets line length, you can also set the --line-length flag
thats not the reason it would be undefined
i want to do ;format [code] and it formats it
Oh, I missed the context
i'm not completely familiar with this but would stringIO work?
How to make a good help command that is not hard coded?
i have __import__("os").system(f"python -m black --code {'embed = disnake.Embed(title=title, description=description, timestamp=timestamp'}")
Oh ok
it's the same right?
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?
Yep, --code is just the human readable
you know that f-string does nothing right?
it raises ```Usage: python -m black [OPTIONS] SRC ...
Try 'python -m black -h' for help.
Error: Invalid value for 'SRC ...': Path '=' does not exist.```
ahh @slate swan i found a fix i didnt know discord.ui.buttons now had a "row=" parameter which helps identify
how to make a help command that is not hard coded???
read pins
help
didnt dpy end?
It was recuntinued a while ago
When?
how do i implement slash commands?
Checkout the links in the channel description
Did dpy 2.0 change something about components? I cant add components anymore:
TypeError: Messageable.send() got an unexpected keyword argument 'components'
What perms would be good enough for a giveaway like how high
Well, normaly you use views.
Make a new_name argument, and then pass into the name argument.
can you send me the most simple one please.
Are you using d.py? Or some fork?
dpy
D.py still don't really haven't implemented it, it's a 2.0 feature.
How do I get 2.0
pip install -U git+https://github.com/Rapptz/discord.py
is there somewhere i can look up view on ?
why did it put the there
Why did you?
sorry I mean why did it not put there since I typed in hello there
Explain that agian please
well, I typed -rename hello there expecting it to rename the channel to #hello-there, but renamed it to hello
Show your code
@commands.command()
async def rename(self, ctx, new_name):
await ctx.channel.edit(name = new_name)```
oh
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
Wasn't that what you did?
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
maybe just try to add buttons one at the time, why do you even need 2 loops to add items
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
it says i do not have git in my path
Personally I use a fork called pycord, I don't know a lot about d.py 2.0.
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?
Discord.py was basically shutdown, so a few forks were made, they have the same syntax but with some improvements.
Nah, nothing.
Oh rah..
I literally don't need to change anything?
What's the error?
I mean, instead of pip install discord.py, do pip install py-cord==2.0.0b4.
Done, it installed.
Yes
How do I do slash commands? like implement them to my commands
You might want to uninstall discord.py and discord.
Uninstall the discord app?
Nah! pip uninstall discord.
Done
I don't think that works
Here is a basic example:```py
import discord
from discord.ext import commands
from discord.commands import slash_command
@slash_command()
async def test(self, ctx):
await ctx.respond("test")
from discord.commands import slash_command <--- that has a yellow line under it
should I be worried?
Nah
Oh, by the way, how do I add the description to the command and name
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
Nah, you should have import discord, pycord have the same syntax as d.py, that's why you needed to uninstall it.
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?
all of my bots code?
Nah, the top where you import stuff
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
- sub to my youtube
- follow my tiktok
- follow my instagram?
If what your asking is how to make it go down a line, do \n
That's basic python: ```py
"""
Line 1
Line 2
Line 3
"""
"Line 1\nLine 2\nLine 3"
alright looks good thanks
remember, basic python doesnt stop people from learning :)
discord bots is a beginner friendly place :)
Yeah, you doesn't seem to be able to install pycord either.
Why can't I install it?
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
It's automatically installing discord.py, overriding pycord.
How do I stop that from happening
What IDE?
vscode
Maybe you should use disnake instead.
Alright, how do I do that
Both
Yes
pip3 install disnake
Do you know if it's necessary to choose the version, like in pycord: pip install py-cord==2.0.0.b4?
no it isn’t
It's just unused, chance everything that says discord to disnake.
Change discord to disnake
disnake.ext.commands
Yes
I did the thing you sent and the thing that maoi sent
?
you have disnake.commandsthat isn’t a valid thing
you can’t get docs for the whole mf extensions command LOL
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
replace all discord with disnake
and do you have disnake installed/right interpreter selected
Or just import disnake as discord
no pls no
that removed a lot of yellow lines but these have yellow lines now
Yeah, but don't add as discord, it will just get overwritten by discord.py, a bunch of extra truble.
How do I know that
🗿
How would you get the Interaction of a button now in dyp 2.0?
💀
I hate this documentation feature
!d disnake.Interaction
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.
!d disnake.ui.Button
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.
disnake?
Discord.py doesn't have 2.0 docs here yet
Yeah they do
Wha
But here
!d discord.ui.Button
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.
Meh
slash commands, buttons, etc
!d discord.SelectOption
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.
That's what I meant
i cant actually find those docs
Change "stable" to "master" in url
Are you in the stable version?
ty : )
You have to make sure it's master
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
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
meh
its open a computer at my school
they didnt shut it down over the weekend
so now its ganna be 3 days
Help! How to create a thread in pycord?
Do you know what's wrong?
If you look at the code, what do you want to happen and when?
i want it to be able to get the guild id of a view before its added to the message
Yes, you use self, but it isn't defined according to Python. Can you tell me the line where self is defined that you want to use?
can that be the reason?
What Button command do i have to put in discord.InteractionType() so it registers a button got clicked
idk what that means
it still wont work.
Can you please format your code to be readable? I can't read that
well i see no error
When you wrote that code, where you wrote it, you wanted to use self.guild_id yeah?
yes
Python is now complaining that it isn't defined, do you think it's (self) defined?
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
How to create a thread in pycord?
documentation
Well, yes, when you're inside a method (a method is a function you defined inside the class)
This does not work
Oh wait, it might be that i made a class the same name with the file im importing
Well, maybe you could link it?
idk where it is
its probably pycord.readthedocs.io or something
1 google search is all it takes
Nvm it is not.
You don't need to keep sending the screenshots again, and again. Is this pycord?
Why say anything then? 🤷♂️
Yes.
i was just saying that searching for it would be quicker then asking here and it saves everyone time
Ah, found it! Have you tried this method? https://docs.pycord.dev/en/master/api.html#discord.Message.create_thread
Yes, but it doesn't work. No error
Which update are you on?
Oh wait, i thought pycord was the same as discord.py, i'm on discord.py sorry about that .
To go back to your issue here, if I understand things correctly, you want code to run when the view is sent with a message? To do this, you tried putting the code inside the class?
Ah, still, what version? I am trying to look at the source
Ok
I do not know why
I'm on version 1.7.3
i try await ctx.message.create_public_thread('Thread', auto_archive_duration = 3600)
what are you trying to do here?
I see you have registered a function as an event and command?
I'm trying to make a command adduser which only i can use to add user IDs to a .txt file.
^^ This is temporary im trying to learn discord.py.
In the feature i will be using MySQL.
okay, and what's app()?
@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.
Do you have an error handler?
nope
okay, well, you don't need that to define a command
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!
and the Commands class should be a cog I guess?
right.
I'm storing the actual commands in other files.
No error and action
to make it look cleaner.
I think I get it now! Your decorators are in the wrong order.
I tried to add, the first one works, the second one doesn't.
actually, you define commands as @commands.command() in a cog
and you have to subclass commands.Cog, not just make a class
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
Try adding a try/except over it, and print the exception.
try:
...
except Exception as e:
print('ran into', repr(e))
You want to wait for an interaction inside of your code?
Do you not want to use views?
i did use views
Then you should have the interaction inside of the button callbacks
TextChannel.create_thread() takes 1 positional argument but 2 positional arguments (and 1 keyword-only argument) were given
how can i access those? this is what i've got so far:
for i in range(3):
for j in range(3):
v.add_item(item=buttons[i][j])
await ctx.send(view=v)
🎉 look at that, an error! Do you understand what it means?
kekw
What's so funny?
nothing
Is buttons a list you have created? Can I see it?
how do i add a status to my discord bot?
What framework do you use?
python
yeah sure 1 sec
# 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"))
Do you see the * at the start? That means something very special, have you seen it before?
buttons = [[None,None,None],[None,None,None],[None,None,None]]
for i in range(3):
for j in range(3):
buttons[i][j] = discord.ui.Button(label="\u200b", row=i, custom_id=("button" + str(i) + "," + str(j)))
okay, you don't look like someone who doesn't know about classes
- subclass commands.Cog
- save your bot to self.bot
- make a command
- 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))
sorry if i'm doing something wrong
Ah, I see. What do you want to do with the button? Just know which button was pressed?
basically yeah
😅
and change it then but that comes after knowing which one got pressed
You are, but it's okay. I wasn't telling you to add the *, I just want to know whether you know what it means - so that I can explain it to you. Do you understand it?
then load extension in the main file
but there's a documentation about cogs in the api reference
* ignores spaces in the argument if I'm not mistaken
i've fixed the issue, but ended up with another one.
It wasn't about classes, it was how i ordered the client.command and @client.event
what
does anyone have a quick name idea for discord bot please
You should probably use the class-way of defining views, are you fine with that? If not, I have some ways we can go around it
bluenix called it and it just doesn't make sense to have an eventcommand for me
tbh i've seen it and i dont really understand it that much it seems a bit too complicated for me
Perhaps you wanted to do py from discord.ext.commands import Bot
?
that's unnecessary memory usage...
anyone please discord bot name
One more question how do i get a users ID?
bot
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.
Thank you ❤️
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.
Which user? There's many users
How come? Modules are only ever imported once 
so he could just remove the event?
A user that has any used the command.
Well, apparently they wanted an event 🤷♂️
ctx.author.id will give you the ID of the person who used the command!
but only specified named events are called 😳
Because what it would allow you to do, is store the button called on the class to use it later. This is more-or-less the only way I can come up with that would make the most sense, let me type out the alternative though
I am looking here but it doesn't seem like discord.py gives you that information: https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Interaction
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*
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.
yeah true



