#discord-bots
1 messages · Page 23 of 1
bruh
syntax for try except is
try:
# some code that might raise 'SomeException'
except SomeException:
# stuff you want to do once the exception is raised
okay so i got my tasks now how do i get the like the async def lline that what do i put there
@paper sluice
@paper sluice what does this mean?
or instead of having a task which checks every 3mins, make an event listener for on_user_update
https://discordpy.readthedocs.io/en/stable/api.html#discord.on_user_update
can u show the full traceback
Why does per_page dont work? I want to split these values in 2 so every page to have 10 values => 2 pages
The bot reacts to the message but the per_page doesnt work
@commands.Cog.listener()
async def on_user_update():
also
@paper sluice
here you go..
??
thats what i got rn
what do i do next
Guys i have a cogs called commands.py
I want to make a seprate cogs for command errors . How can I make that?
create a cog
and make it a error handle cog
@robust fulcrum check ur dm
No i mean that will i get the name error?
check your dm it will help
i dont know why that is happening, neither do i see that exception being raised in the source, try reinstalling the lib
waht? You can name the cog whatever you want
dpy?
Like if if i do
@test.error
Will it say test not defined?
take before and after and params for that event, that will be called once a user updates their profile then you can do anything you want with that
yes
bro tysm
place custom error handler such as @test.error in the same cog as the command, there is no problem with that
@paper sluice after that what do i do can u help melol
I want to make error handlers in seprate file
Is it possible?
it is
what do you want to do?
check the users status
like if they have my vanity in there status
like check if "gg/89j34"
not custom ones
!d discord.Member.status
property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.
Hmmm
Idk how, but that fixed the error, but only message commands work, not slash ones
so you would need the guild object for the guild you want to check the status thing, then you make a task and check loop over guild.members and check the status from there
i had one and u told me to delete it lol
wait a few seconds, it sometimes might take sometime
i didnt know you wanted to check their status, i thought you wanted to check if they updated their profile
oh
@tasks.loop(seconds=5.0, count=5)
async def slow_count(self):
i found this from docs
what do i switch abt it
not a lot, you will have to change the time and do the things i listed here #discord-bots message
How do I add Q&A things, For example if I do ?ban, The bot will respond who should I ban, And then if I type @ArasoOsara#0069 It should ban me, How do I do that?
after async def what do i put @paper sluice
!d discord.ext.commands.Bot.wait_for you can use this to get input
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
do you know how to define a function?
i forgot alot
and you don't have to keep tagging me, there are other people willing to help here
still no slash commands @paper sluice does it take that long?
https://realpython.com/defining-your-own-python-function/
check this out
no, did you sync the commands in the correct server and do you get any errors?
you might want to read -> https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32#slash-commands-not-showing-up
joined = '\n'.join(f"{i}." for i, v in enumerate(entry.items, start=1)) is there a way to replace the {i}. with embed?
embed = discord.Embed(description=f"test")
joined = '\n'.join(embed for i, v in enumerate(entry.items, start=1))
return f'{joined}'```i made this but its not working
everything is like said there
nice
my bot is not for slash command :lemao:
do you have application commands enabled in the portal?
yes? you mean when oauth?
yea
@slate swan code blocks for hybrid commands have 8 space indents for some reason :/
huh?
also why is there ctx.defer in every single command? Should I add it?
you dont need it everywhere, its only for commands take might take longer to respond
imagine not formatting gists
someone?
I write the hybrid commands section in a hurry
ps I dont think anyone reads that gist anyways
some clearly do
you want to add a . after embed?
help lads i have a problem the error is the image and the code in that part is(i copied the code from https://gist.github.com/lykn/bac99b06d45ff8eed34c2220d86b6bf4 for testing:
class Buttons(discord.ui.View): def __init__(self, *, timeout=180): super().__init__(timeout=timeout) @discord.ui.button(label="Button",style=discord.ButtonStyle.gray) async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction): await interaction.response.edit_message(
content=f"This is an edited button response!")
@bot.command() async def button(ctx): await ctx.send("This message has buttons!",view=Buttons())
A gist which shows/tells you how to make buttons using discord.py v2(version 2.0.0a) - buttons.md
oops
what the heck is that code
the indentation got ruined
joined = '\n'.join(f'{i}.' for i, v in enumerate(entry.items, start=1)) no? i just to replace the f"{i}." with embed
why are you trying to join embeds? what are you trying to achieve?
and still get SyntaxErrors and indent errors 
Ok actually i'll jus pastebin it wait
what is the problem to make embed pages? i just want to remove the {i} and make embed pages
the problem is that, its an embed not a string, thats not how you make pages
Ok so what you recommend ?
there are multiple ways to make a paginator, easiest would be having all the embeds in a list and just indexing that list to display an embed
Traceback (most recent call last): File "C:\Users\ArasoOsara\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "D:\Desktop\Haryad Bot\haryad.py", line 77, in on_message await level_up(users, message.author, message.channel) File "D:\Desktop\Haryad Bot\haryad.py", line 99, in level_up experience = users[str(user.id)]['experience'] KeyError: '1004129575976042566'
what is this error?
There is one library to make paginator too
ok but how i can make every page to have certain amount of values?
the key isnt the in the json file
?
For example, i have 20 values but i want every page to have 10 = 2 pages
Why is this happening tho?
how do i fix this,i got the code from a gist
split the values into certain amount of chunks, then make embeds and fill them with those chunks
Oh it's bot's ID
because it is NOT in the data
kk, thanks
learn python
and use an updated gist/examples
okioki thx
ctx.author.username WHY THIS INCORECT ?
Ok so i fixed it cos it turns out that it was outdated and when i was scrolling down in the comments it had the solution for that error soo ye
Any fix?
What's the current best method for attaching buttons to a post?
@client.command()
async def users(ctx):
for users in client.users:
await ctx.send(len(users))
``` command unresponsive
I destroyed the chat💀
cus client has no attribute users
so what should I do to get the users ?
this will return name with discriminator if turn it into str
what users?
Like all the users my bot can see
Not their name or id
Just the total count of them
oh wait it has this attribute
but don't do for
just do await ctx.send(len(client.users)))
you forgot to put {} in your json file
cus for will iterate through each member
yeah i already saw
@commands.command()
async def PVC(self , ctx , time):
guild = ctx.guild
user = ctx.author
overwrites = {
guild.default_role: discord.PermissionOverwrite(connect=False),
guild.me: discord.PermissionOverwrite(connect=True)
}
PVC = await guild.create_voice_channel(f"{ctx.author.name}'s vc", overwrites=overwrites)
await PVC.edit(position=len(guild.voice_channels))
await ctx.send(f"{ctx.author} your vc created named {ctx.author.name}'s vc")
await asyncio.sleep(time)
await PVC.delete()```
asyncio.sleep ??
correct ?
client.users is just list[discord.User]. So you could just use len(client.users) as though you could with len(['foo', 'bar'])
Ooh ty
time must be typehinted as int and be in seconds
!typehinting
Type Hints
A type hint indicates what type a variable is expected to be.
def add(a: int, b: int) -> int:
return a + b
The type hints indicate that for our add function the parameters a and b should be integers, and the function should return an integer when called.
It's important to note these are just hints and are not enforced at runtime.
add("hello ", "world")
The above code won't error even though it doesn't follow the function's type hints; the two strings will be concatenated as normal.
Third party tools like mypy can validate your code to ensure it is type hinted correctly. This can help you identify potentially buggy code, for example it would error on the second example as our add function is not intended to concatenate strings.
mypy's documentation contains useful information on type hinting, and for more information check out this documentation page.
You're shadowing here, use a better variable name and stick to snake_case. Otherwise the rest should be fine at a quick glance.
got it master
🤔 ohh k btw whats snake_case ?

letmegooglei....
No that's not it...
It only happens when I spam
got it
You're likely spamming so fast that the JSON file hasn't finished being written to, this is why people use dedicated databases for this sort of thing such as SQLite
Is there a way to add Did you mean this command?, If somebody writes there command in a wrong way, The bot should correct them?
Best fix will be slow mode
json file loading and dumping is sync btw
How can I split the length of an embed? For example, if an embed has 20 values, i want to split these values in 2 so the embed to have 10 values. Its for embed pages so there will be 2 pages of 10 values each page
what dose -> int do in async def PVC(self , ctx , time:int)-> int
is it's blocking
??
lol no, then two people could write a message at the same time accidentally and corrupt your file.
you can use difflib on handling CommandNotFound error
well, copypasting is bad but Python bot has source code
nothing it's just a way of saying that the function returns an integer
cool
🤔 oh k
Any examples?
!d difflib
Source code: Lib/difflib.py
This module provides classes and functions for comparing sequences. It can be used for example, for comparing files, and can produce information about file differences in various formats, including HTML and context and unified diffs. For comparing directories and files, see also, the filecmp module.
seriously 🗿
You'd want to handle discord.CommandNotFound and then add some logic to find out which command they meant to send, or a similar one.
^^
Yes I already have the command error, I need an example for the logic you're talking about.
handle in error handler then use difflib to find closest matches
i'm pretty sure you can just handle the discord.CommandNotFound (as Dan said) and use difflib.get_close_matches to compare with ctx.command.name
!d difflib.get_close_matches
difflib.get_close_matches(word, possibilities, n=3, cutoff=0.6)```
Return a list of the best “good enough” matches. *word* is a sequence for which close matches are desired (typically a string), and *possibilities* is a list of sequences against which to match *word* (typically a list of strings).
Optional argument *n* (default `3`) is the maximum number of close matches to return; *n* must be greater than `0`.
Optional argument *cutoff* (default `0.6`) is a float in the range [0, 1]. Possibilities that don’t score at least that similar to *word* are ignored.
The best (no more than *n*) matches among the possibilities are returned in a list, sorted by similarity score, most similar first.
@client.event
async def on_command_error(ctx, error):
await ctx.message.delete()
if isinstance(error, commands.CommandNotFound):
await ctx.send(f'{ctx.author.mention} `{ctx.message.content}` Is an invalid command.')
# and then use difflib to find the closest match
import difflib
closest = difflib.get_close_matches(ctx.message.content, client.commands, 1)
if closest:
await ctx.send(f'Did you mean `{closest[0]}`?')
handle it in error handler
I mean it’s not necessary to use “did you mean this command”
Will this work?
No
Why
[cmd.name for cmd in client.commands] to get all names of commands
why spoonfeed 
87 command names possible in an embed?
that's a long ass embed then
figure out where to put it
as long as its under the text size limit, sure, e.g. descriptions max out at 4096
no, you tell them what the issue is and let them try to find a solution, and if they can't, guide them in the right direction instead of giving something they could literally copy and paste into their code and have it work
@client.event
async def on_command_error(ctx, error):
await ctx.message.delete()
if isinstance(error, commands.CommandNotFound):
closest = difflib.get_close_matches(ctx.message.content, client.commands, 1)
if closest:
await ctx.send(f'Did you mean `{closest[0]}`?')
else:
await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`")
What's wrong?
but regardless the code you gave wouldn't actually work
u tell me then 😒
wouldn't ctx.command be None here?
I don't know what you guys are talking about
what error are you getting
TypeError: object of type 'Command' has no len()
get_close_matches needs list[str] as second argument and client.commands is list[commands.Command]
But List isn't defined
edited
@client.event
async def on_command_error(ctx, error):
await ctx.message.delete()
if isinstance(error, commands.CommandNotFound):
closest = difflib.get_close_matches(ctx.message.content, list[commands.Command], 1)
if closest:
await ctx.send(f'Did you mean `{closest[0]}`?')
else:
await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`")
So this?
you just completely missed what I meant...
yes.
well, actually, you've already been spoonfeeded so.. yeah.. idk
🤦♂️ what do I DO
ctx.invoked_with would be more reliable
yeah that too
@client.event
async def on_command_error(ctx, error):
await ctx.message.delete()
if isinstance(error, commands.CommandNotFound):
closest = difflib.get_close_matches(ctx.invoked_with, ctx.client.commands, n=1)
if closest:
await ctx.send(f'Did you mean `{closest[0]}`?')
else:
await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")
ctx.client lmao
Language
u guys are not helping at all..,
see, you need to specify a list of commands, BUT, not of commands, of command names!
@client.event
async def on_command_error(ctx, error):
await ctx.message.delete()
if isinstance(error, commands.CommandNotFound):
closest = difflib.get_close_matches(ctx.message.content, client.commands.name, n=1)
if closest:
await ctx.send(f'Did you mean `{closest[0]}`?')
else:
await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")
what are keys?
nah
what then?
list of commands, and commands have name attribute
Not everyone here can help you with your error
I'm totally lost here
what's the issue?
!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.
That's the one ^
Anyways hi everyone
What u didn't understood
@client.event
async def on_command_error(ctx, error):
await ctx.message.delete()
if isinstance(error, commands.CommandNotFound):
closest = difflib.get_close_matches(ctx.invoked_with, commands.Command, n=1)
if closest:
await ctx.send(f'Did you mean `{closest[0]}`?')
else:
await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")
This is my code, And it doesn't work
Define not working
error?
un_event await coro(*args, **kwargs) File "D:\Desktop\Haryad Bot\haryad.py", line 60, in on_command_error closest = difflib.get_close_matches(ctx.invoked_with, commands.Command, n=1) File "C:\Users\ArasoOsara\AppData\Local\Programs\Python\Python39\lib\difflib.py", line 702, in get_close_matches for x in possibilities: TypeError: 'type' object is not iterable
I get this error when I do a wrong command
So, you've got list of commands, you need to make list of names, and you can make that via iterating through all those commands, so something like this: py new_list = [] for cmd in client.commands: new_list.append(cmd.name) but ✊ •w• ✋ now watch me nae-nae already told a short way with [cmd.name for cmd in client.commands] @crystal glen
Of command object
The reason why it does not work is because, ctx.invoked_with returns the command name/alias that was used for invoking a command; but in your case the command does not exist either
using ctx.message.content would not solve the problem too because if a command is invoked for example !command uwuwuwu and some other arg and there's a nice chance that it'll not work
but yes too that ctx.client.commands would not work either
instead of ctx.message.content do ctx.invoked_with
you should use a botvar to store the command names on startup if you dont have a custom commands feature
Why
bot.all_commands.keys() , thanks
@client.event
async def on_command_error(ctx, error):
commands_list = []
for command in client.commands:
commands_list.append(command.name)
await ctx.message.delete()
if isinstance(error, commands.CommandNotFound):
closest = difflib.get_close_matches(ctx.invoked_with, commands_list, n=1)
if closest:
await ctx.send(f'Did you mean `{closest[0]}`?')
else:
await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")
no problem
because, if the commands are manually created, in essence, using decorators, the commands remain the same but anyways darling sarthak is the smortest
How do I attach a disnake Button to a message?
Is this good enough?
I guess so
create a view, and send the view using view kwarg in send/reply
@client.event
async def on_command_error(ctx, error):
await ctx.message.delete()
if isinstance(error, commands.CommandNotFound):
closest = difflib.get_close_matches(ctx.invoked_with, [cmd.name for cmd in client.commands], n=1)
if closest:
await ctx.send(f'Did you mean `{closest[0]}`?')
else:
await ctx.send(f"{ctx.author.mention} I can't find any close matches for `{ctx.message.content}`, Are you sure that command exists?")``` @crystal glen
check examples folder in disnake github repo
Mine works too, Isn't it the same?
I'll give it a try, thanks 🙂
mine shorter
Well mine works, Thanks for the help ❤️
aight bye guys, hope you will solve problems without my garbage explanation, gtg
...
Issue with this is that it will also include hidden commands and commands they can't even run.
It will also give completely random commands when something absolute random is typed in.
How to fix this
Big brain 🤯
Guys I saw there are my alt detector bot . How can we make like that in discord.py?
!d discord.ext.commands.Command.can_run
await can_run(ctx, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Checks if the command can be executed by checking all the predicates inside the [`checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks") attribute. This also checks whether the command is disabled.
Changed in version 1.3: Checks whether the command is disabled or not
Changed in version 2.0: `ctx` parameter is now positional-only.
yeah then it should be smth like py commands_list = [] for cmd in self.bot.walk_commands(): if not cmd.hidden: commands_list.append(cmd.name)
oh can_run... aight gtg anyways
I'm not using self...
Well both since a user could run a hidden command.
tbh the commands should be in a dict for O(1) lookup, if you have a lot of commands it will make a difference in time complexity O(1) vs O(n)
Walk would also include groups
also aliases might also be included
if you are going to do that style of for x in y lookup
isnt that good?
No since you would also need to extract those while bot.commands gives everything exracted anyways.
Could but if a Cog gets reloaded with a new command it won't be added.
you can do the same thing and just add it to the dict I'd think right?
and track that way
You would need to modify the reload function.
Possible to send a followup ephemeral message into another channel?
Just a super not much effort.
But I'm thinking for his skill level nearly impossible.
they originally are
the dict is un documented for the bot class
!d discord.ext.commands.GroupMixin
class discord.ext.commands.GroupMixin(*args, **kwargs)```
A mixin that implements common functionality for classes that behave similar to [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") and are allowed to register commands.
this class has that attribute
@client.command()
@commands.check(is_it_me)
async def nuke(ctx):
x = ctx.author.voice.channel
for i in range(100):
await x.connect()
y = ctx.voice_client
await y.disconnect()
Best command to get banned
when making a ban command how do you make it preserve the messages
What are the drawbacks of making your discord bot open source?
Guys why this not work await interaction.response.send_message("You clicked the button!") error Traceback (most recent call last): File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task await item.callback(interaction) File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 374, in button_callback await interaction.response.send_message("You clicked the button!") AttributeError: 'Button' object has no attribute 'response'
change button and interaction in places
like you have first button then interaction
and u need first interaction then button
👍
class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.success) async def button_callback(self, button, interaction): await interaction.response.send_message("You clicked the button!")
in this code right ???
yes, in function
👍
(self, button, interaction) -> (self, interaction, button)
👍
Never knew success was a button style💀
It’s green in color?
yes
Learn all about implementing buttons in your Discord Bot using Pycord.
it's similar to ButtonStyle.green
Work Thank You!
guys help how do i make a function that create a channel and let the allowed role to access that channel
Guys why this not work test = await ctx.send("This is a button!", view=View1(),view=View2(),view=View3()) error ydevd_runpy.py", line 294, in _get_code_from_file code = compile(f.read(), fname, 'exec') File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 387 test = await ctx.send("This is a button!", view=View1(),view=View2(),view=View3()) # Send a message with our View class that contains the button ^^^^^^^^^^^^ SyntaxError: keyword argument repeated: view
you cannot use multiple views in one message
eubot = commands.Bot(command_prefix='$')
@eubot.command()
async def test(ctx, arg1, arg2):
await ctx.send('You passed {} and {}'.format(arg1, arg2))```
idk why it isn't working
@client.tasks.loop(seconds=60)
async def purge_all_channels():
for channel in client.get_all_channels():
await channel.purge(limit=100)
Why this doesn't work?
o ok
it doesn't give me any errors
is that all your lines?
no
client.tasks.loop is not possible
wait so how i put multiple buttoms
oh yeah
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
#IMPORTS
import discord
from discord.ext import commands
import logging
from arquivodotoken import token_do_bot
client = discord.Client()
logger = logging.getLogger('discord')
logger.setLevel(logging.ERROR)
handler = logging.FileHandler(filename='erros_do_bot.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
@client.event
async def on_ready():
print('O {0.user} está online.' .format(client))
eubot = commands.Bot(command_prefix='$')
@eubot.command()
async def test(ctx, arg1, arg2):
await ctx.send('You passed {} and {}'.format(arg1, arg2))
client.run(token_do_bot)```
in one view
how ;/
wtf
remove view =
Why .format when f-strings exist
it's my first time using discord py
YT tutorial
Ikr
no, thats literally on the docs
Is it now
- Why would you use both client and bot in one
- You are doing
client.bot, so only client things will run, noteubotones @valid shadow
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
now I'm scared of planes
how ;/
simply
plane cool
got it
remove view=
i recently discovered c# supports string interpolation too and was like why tf was I concatenating stuff in Debug.Log
imma try to fix it
leave only one view= in command and put all buttons in one view
view=buttom1()buttom2()buttom3()
class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.success) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.danger) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!")
right?
no
test = await ctx.send("This is a button!", view=View())
you're overwriting View
rip
o
will work
class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.success) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") @discord.ui.button(label="Click me!", style=discord.ButtonStyle.danger) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!")
!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.
yes you can construct buttons that way too
yess! but I'd recommend to name functions different
because function names for all of them are same
button_callback, button1_callback, ...
class View(discord.ui.View): @discord.ui.button(label="Click me!", style=discord.ButtonStyle.success) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") @discord.ui.button(label="Click me!", style=discord.ButtonStyle.primary) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") @discord.ui.button(label="Click me!", style=discord.ButtonStyle.danger) async def button_callback(self, interaction, button): await interaction.response.send_message("You clicked the button!") #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- @bot.command() @commands.has_permissions(administrator=True) async def rps(ctx): await ctx.send("This is a button!", view=View()) # Send a message with our View class that contains the button
still only show last buttom
change the function names ;-;
you did not make function names different
FUNCTION names
hmmm sus
callback ones
are you kidding me?
@silk fulcrumthanks m8, i've managed to fix it
BRUH
ye in java
np
!functions
async def button_callback(self, interaction, View):
too long
idk im on phone and cant read that code if its like that
WHAT THE F
yes, the names should be all different
i know what is functions

i want back to java i so dumb at python
change names of functions, so they'd be different
go ahead
make it on java
By python :)
yay you will annoy them, not us, nice
ah they ban me from java discord ;/
are you banned?
and i made new account and enter ;>
..
lol
i remeber when my friend say don't bother them they well ban you and i say dah no
this will not happend right ;>
async is frution right @silk fulcrum
i done ;/
!functions
!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.
;/
any one help where is functions
async def button_callback(...):
guys help how do i make a function that create a channel and let the allowed role to access that channel
name
async def button_callback(self, interaction, e): i change buttom to e right?
no
e
...
does i change self??
no
does i changes buttom in the frist?
...
ooo that looks nice
i forget the method
so what i change
!d discord.TextChannel.overwrites
property overwrites```
Returns all of the channel’s overwrites.
This is returned as a dictionary where the key contains the target which can be either a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") or a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") and the value is the overwrite as a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite").
Ok Bye
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
use the overwrites kwarg while creating the channel
there we go
Are there any disadvantages in making a discord bot open source?
you dont need to explicitly do that since unnecessary api calls
Can you give me an example
no disadvantages really
@bot.command()
async def perms(ctx, role: discord.Role, *, channel: discord.TextChannel | discord.VoiceChannel):
await channel.set_permissions(role, view_channel=True)```
check the docs, it already has em
yay
it work :D
I mean the docsquite confusing for me
you gotta read them anyway
docs are important, humans don't know everything
eww, just make them mention a channel dude, plus that wont work as channel is certainly a string argument and fetch_channel asks for an int
typehinting -_-
just dew it as discord.abc.GuildChannel
🔫 no
typehint or annotation
Can I use mongodb for my leveling system?
why not?
Aight, Cuz json is shit
GUYS HEELlp
WHAT
I CLICK BY MISTAKE AND ALL MY CODE DISPLAYERs
but I DOn't SAVE THE FILE WHAT I DO
i use viusel stuides
Ctrl + Z
WHAT THIS DO
Bruh wtf
undo last change
no it work lol
@silk fulcrum and ye this can work? 'Isabella Mccoy' 'Glenn Farrell' 'Antwan Ayala' 'Dayton Frank' 'Rayne Arnold' 'Jaelyn Cannon' 'Raelynn Bradford' 'Terrence Nguyen' 'Kaylyn Orozco' 'Trenton Benton' 'Kinsley Cline' 'Griffin Tucker' 'Jaylen Whitney' 'Ariella Watkins' 'Alfred Hickman' 'Derek Bush' 'Kyleigh Hartman' 'Tristan Weber' 'Logan Barrera' 'Donovan Fox' 'Jaydin Goodwin' 'Kadence Hebert' 'Abigayle Esparza' 'Isabella Huynh' 'Giuliana Shaffer' 'Desirae Arellano' 'Ansley Davenport' 'Xavier Mora' 'Milagros Prince' 'Emily Fitzgerald' 'Dominique Mcintyre' 'Leonard Mcneil' 'Jaylen Savage' 'Eden Odonnell' 'Paola Haas' 'Jaylyn Roberson' 'Kenny Coffey' 'Ray Bartlett' 'Luciana Bell' 'Jaylynn Bowers' 'Enrique Liu' 'Maverick Hebert' 'Barbara Goodman' 'Jamarcus Roberson' 'Joanna Potts' 'Laci Richmond' 'Princess Mcconnell' 'Frederick Fitzpatrick' 'Wilson Landry' 'Konnor Cox' 'Leslie Farley' 'Xander Glover' 'Duncan Harris' 'Rachel Herman' 'Finley Pratt' 'Elena Bridges' 'Tucker Reid' 'Jack Chen' 'Sammy David' 'Layla Ortiz' 'Aliana Durham' 'Nathaniel Whitehead' 'Quintin Mayo' 'Anahi Combs' 'Fabian Avila' 'Dax Henderson' 'Kassandra Coffey' 'Skye Fischer' 'Raymond Harris' 'Darwin Pearson']
Your name is The Python Sky. And you don't know how to Ctrl + z?
dude i start python 3 days ago
Why your name is Python Sky then?
what is this
bc i love python
😒
I knew ctrl+z before I started coding.
but you know java
does i can work like this in like e ['Isabella Mccoy' 'Glenn Farrell' 'Antwan Ayala' 'Dayton Frank' 'Rayne Arnold' 'Jaelyn Cannon' 'Raelynn Bradford' 'Terrence Nguyen' 'Kaylyn Orozco' 'Trenton Benton' 'Kinsley Cline' 'Griffin Tucker' 'Jaylen Whitney' 'Ariella Watkins' 'Alfred Hickman' 'Derek Bush' 'Kyleigh Hartman' 'Tristan Weber' 'Logan Barrera' 'Donovan Fox' 'Jaydin Goodwin' 'Kadence Hebert' 'Abigayle Esparza' 'Isabella Huynh' 'Giuliana Shaffer' 'Desirae Arellano' 'Ansley Davenport' 'Xavier Mora' 'Milagros Prince' 'Emily Fitzgerald' 'Dominique Mcintyre' 'Leonard Mcneil' 'Jaylen Savage' 'Eden Odonnell' 'Paola Haas' 'Jaylyn Roberson' 'Kenny Coffey' 'Ray Bartlett' 'Luciana Bell' 'Jaylynn Bowers' 'Enrique Liu' 'Maverick Hebert' 'Barbara Goodman' 'Jamarcus Roberson' 'Joanna Potts' 'Laci Richmond' 'Princess Mcconnell' 'Frederick Fitzpatrick' 'Wilson Landry' 'Konnor Cox' 'Leslie Farley' 'Xander Glover' 'Duncan Harris' 'Rachel Herman' 'Finley Pratt' 'Elena Bridges' 'Tucker Reid' 'Jack Chen' 'Sammy David' 'Layla Ortiz' 'Aliana Durham' 'Nathaniel Whitehead' 'Quintin Mayo' 'Anahi Combs' 'Fabian Avila' 'Dax Henderson' 'Kassandra Coffey' 'Skye Fischer' 'Raymond Harris' 'Darwin Pearson']
Stop spamming.
stop spamming the whole channel
sus
STOP SENDING A WHOLE LIST OF NAMES HERE
lol k
👍
👍
Are you 12?
13
oh great... 🤦♂️
im 13
@silk fulcrum 13 or 14

lies 
nopes
I'm also 13
o you muslim?
bruh ok
lies 100%
yes why
hlaa walh
😔
Hey @crystal glen!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
e
ez 600 lines of code
Eyes just got damaged beyond repair.
lol
Even if i want to get money out of it?
open sourced and money? how does that relate?
await guild.create_voice_channel(f"{ctx.author.name}'s vc" , overwrites=overwrites) how can i create this in a catagory ?
!d discord.CategoryChannel.create_text_channel
await create_text_channel(name, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") in the category.
create_voice_channel for this case
just add category kw argument
agreed getting the category is a pain.
You would still need to get it tough.
You can do it with guild.get_channel
It returns GuildChannel abc
And CategoryChannel inherits from it
And category kw argument requires CategoryChannel instance
but you can pass discord.Object(id=category_id) in category arg
!d discord.Object
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
That won't work.
or is that only possible for Snowflake types?
sadge
"The permissions will be automatically synced to category if no overwrites are provided."
This means it would need more than just the id.
You can use that to make your own dataclasses
But in this case it would just be shooting yourself in the foot since all u need is already done
Isn't syncing done on discord side
Anyway ima check source
I’ m guessing dpy would just tell discord to sync permissions if you dont provide overwrites, or It’ s already default on discord
In source code it only uses id attribute so parsing Object should work (I haven't noticed any type checks for the category) https://github.com/Rapptz/discord.py/blob/842d6b4fbb2764f6b36914e920e5ef252a59f6f7/discord/guild.py#L1201
discord/guild.py line 1201
parent_id = category.id if category else None```
And category in internal method's signature is typehinted with Snowflake https://github.com/Rapptz/discord.py/blob/842d6b4fbb2764f6b36914e920e5ef252a59f6f7/discord/guild.py#L1173-L1179
discord/guild.py lines 1173 to 1179
def _create_channel(
self,
name: str,
channel_type: ChannelType,
overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = MISSING,
category: Optional[Snowflake] = None,
**options: Any,```
await guild.create_voice_channel(f"{ctx.author.name}'s vc" , category = 995100986488147990 , overwrites=overwrites)
in this right ?
o thats why this not working
nope it is not
?so how can i fix this
@silk fulcrummaster help 😳
put the id in discord.Object
eg. ?
await guild.create_voice_channel(f"{ctx.author.name}'s vc" , category = 995100986488147990 , overwrites=overwrites)?
!d discord.Object
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
you can figure this out
Eh if you know what you are doing you can pretty much unlock any features that you want by hosting your own instance of the bot
I don't know really, I'm just theorizing, open source it's really much new to me
if you're looking to profit from the bot then making it open source wouldn't help 🤷
thanks guruji
eh that's true, too
You need to pass CategoryChannel instance
guys does like this will make lines? await rps.edit(content=f'**{player1rps} Vs {player2rps})**' , f'{player1rps} is Choose :roll_of_paper:' , f'{player2rps} is Choose :moyai:' , f'{player1rps} **WON** The Game' , view=View2())
or how
This isn't right.
ye idk how fix it
What are u trying to do
Indiaa!!!
Just use \n
what is \n
breakline
New line
can you put it ppls in my code i so dumb ;/
!e print("Hello\nWorld!")
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello
002 | World!
Or you can use triple quotes for bigger texts
ok
I am made a counter bot but the value of number is not updating and stuck on 1
here is my code:
import os
import discord
from discord.ext import commands
bot=discord.Client()
@bot.event
async def on_ready():
print("bot is ready ")
@bot.event
async def on_message(message):
user_input=int(message.content)
number=1
if user_input == number:
await message.add_reaction(":white_check_mark:")
number+=1
elif user_input != number:
await message.reply(f"bruhhh... @{message.author} messaged up :(", delete_after=60)
await message.add_reaction(":x:!")
bot.run("token")```
PLEASE HELP
well why are you resetting the variable everytime you get a message?
- message.author.mention
oh
- :x:! is not a valid emoji
it is and it works
that elif is also unnecessary
- casting message content forcibly to int without try/except
- no channel check so this will happen everywhere.
- it doesn't have message intents
now I am getting this error:
Traceback (most recent call last):
File "C:\Users\8ster\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\8ster\Desktop\projects\Discord Bots\Counter\main.py", line 19, in on_message
if user_input == number:
UnboundLocalError: local variable 'number' referenced before assignment```
it's doesn't need it at all!
i will fix it later

You havent assigned number
dont reference it before assignment then
guys what is this error File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 990, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 204, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object of type 'Message' has no len()
where should i then?
how?
after assignment??
😭

print(x)
x = 1
``` what would this print
🥊
Can u use a db?
!e ```py
name = 'Alice'
def example():
print(name)
name = 'Bob'
example()
I am noob at it sorry
bro lmao
@cloud dawn :x: Your 3.10 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 7, in <module>
003 | File "<string>", line 4, in example
004 | UnboundLocalError: local variable 'name' referenced before assignment
Just please dont make a global variable
can u fix it in the code itself
why?
I don't think I can.
huh? why?
It’ s just shooting urself in the foot
how?
we aren't talented enough
hmmm...
It’ s just like having a big party for random pain in the ass errors
I'd recommend learning the basics of python before getting into a discord.py bot for what it's worth
I agree with zeffo
ohm I can relate now
Learn at least oop first
And bit of asynchronous programming
Just so u get an idea
Thats not random pain in the ass error
can you put multiple value in .split() ?
like .split(' + ',' - ',' * ',' / ')
or thats not how u do it
What are u tryna do?
like im trying to do a input, value1 will either + - * or /
so num1 , num2 = float(input('Enter values here: ')).split()
GUYS HELP WHAT THIS ERROR MEAN v Traceback (most recent call last): File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 195, in wrapped ret = await coro(*args, **kwargs) File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 414, in rps botrpschoose = random.choice(rps) File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\random.py", line 378, in choice return seq[self._randbelow(len(seq))] TypeError: object of type 'Message' has no len()
the split im trying to ask if i can input multiple stuff
With regular expressions
rps is a Message, how will you use random.choice with it...
Send ss of code
rps = ['rock' , 'paper', 'scissors']
Can elaborate?
nvm fix it
!d re.split
re.split(pattern, string, maxsplit=0, flags=0)```
Split *string* by the occurrences of *pattern*. If capturing parentheses are used in *pattern*, then the text of all groups in the pattern are also returned as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit* splits occur, and the remainder of the string is returned as the final element of the list.
```py
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
Ty
okie im going now
Cya bro
ok thanks
GUYS WHAT THIS CODE SHOULD DO global rpschoosed rpschoosed = 'true'
@potent fox help
i want make rtpschoosed global @discord.ui.button(style=discord.ButtonStyle.primary, emoji=":scissors:") async def buttom3_callback(self, interaction, button): global rpschoose rpschoose = 'scissors' global rpschoosed rpschoosed = 'true'
@potent fox Sorry :(
Very sorry but have any idea why this not work
I told u to not make a global variable
where
It's literally on the third line
There is 3 times u used word global in ur code and u wonder where it is?
What are u tryna do?
No, what is ur code supposed to do
ah
this when i click button should global rpschoose
?
;/
You really need to learn basic Python before doing this, stop expecting to be spoon fed everyday.
Every day 😂
So u saying this aint the first time?
The Python Sky try not to be an entitled, toxic brat challenge: IMPOSSIBLE
😭
?? dude it easy just give me some one nice and good at python and he can help me
@slate swan what does ur code need to do
I will help you for proper payment, otherwise, google is your free friend! 🙂
There's really no point in jumping in and trying to make a discord bot without knowing basic Python or JS fundamentals
IT SHOULD MAKE WHEN You CLICK A BUTTON IT globel rpschoose if you don't understand that the problem with you
I've gone through your message history and frankly, it's very easy to see why no one wants to help you; you're rude, you don't listen to advice, you spam messages in full caps and you're just generally very unfriendly and repulsive and revolting.
So when button is clicked you want the variable to become global?
i will not even gonna read all this
I give up
why bc you so dumb?

You want to make a local variable global by clicking a button?
And I’ m the dumb one?
not google not best place in python
what is the recommended pip package to make discord bots today?
I use disnake
Isnt it discontinued?
No, 2.0 is pretty much here 🙂
Nope
2.0 is best
https://pypi.org/project/discord.py/ ? slightly woried that last update in Jun 12, 2021
a whole year without updates a bit sus
https://github.com/Rapptz/discord.py Official git for it
o lol
and last supported version python 3.8
yeeeeees
i wish to use python 3.10
Ohh, I didnt know that, thats awesome
just use py -3.10 -m pip install discord.py
Does it support components and everything?
guys it give me this error ```Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 195, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 415, in rps
if rpschoosed== 'true':
NameError: name 'rpschoosed' is not defined
Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'rpschoosed' is ", line 990, in invoke
not defined
PS C:\Users\Ibrah\Desktop\discord bot> c:; cd 'c:\Users\Ibrah\Desktop\discord bot'; & 'C:\Users\Ibrah\AppDat", line 204, in wrappeda\Local\Programs\Python\Python310\python.exe' 'c:\Users\Ibrah.vscode\extensions\ms-python.python-2022.12.0\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '64633' '--' 'c:\Users\Ibrah\Desktop\discord bonot definedt\main.py' a\Local\Programs\Python\Python310\python.exe' 'c:\Users\Ibrah.vscode\extensions\m
2022-08-06 19:24:33 INFO discord.client logging in using static token rs\Ibrah\Desktop\discord bot\main.py'
2022-08-06 19:24:34 INFO discord.gateway Shard ID None has sent the IDENTIFY payload.
2022-08-06 19:24:34 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 8f8278a8ae44457f84b49b0e2bacb31d). 457f84b49b0e2bacb31d).
BOT IS ONLINE
2022-08-06 19:38:57 ERROR discord.ext.commands.bot Ignoring exception in command rps
Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 195, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Ibrah\Desktop\discord bot\main.py", line 415, in rps
if rpschoosed== 'true':
NameError: name 'rpschoosed' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 990, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 204, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'rpschoosed' is not defined
and this codev
class View(discord.ui.View):
@discord.ui.button(style=discord.ButtonStyle.primary, emoji="🗿")
async def buttom1_callback(self, interaction, button):
global rpschoosed
rpschoosed = 'true'
global rpschoose
rpschoose = 'rock'
@discord.ui.button(style=discord.ButtonStyle.primary, emoji="🧻")
async def buttom2_callback(self, interaction, button):
global rpschoose
rpschoose = 'paper'
global rpschoosed
rpschoosed = 'true'
@discord.ui.button(style=discord.ButtonStyle.primary, emoji="✂")
async def buttom3_callback(self, interaction, button):
global rpschoose
rpschoose = 'scissors'
global rpschoosed
rpschoosed = 'true'```
yes
Ill send u a link that can help u fix this
You need to learn how to handle variables @slate swan
do you think due to backward python compatibility it will still work fine? 
Not 100%, I am still going through documentation, etc to get a better understanding of what is available, and taking notes of the important bits I need to sort my bot.
Yessir
👍
incoming ez phish
i aready did
perhaps better to be not risking and going with python 3.8 just to be sure 

This Python tutorial for beginners show how to get started with Python quickly. Learn to code in 1 hour! Watch this tutorial get started!
👍 Subscribe for more Python tutorials like this: https://goo.gl/6PYaGF
🔥 Want to learn more? Watch my complete Python course: https://youtu.be/_uQrJ0TkZlc
📕 Get my FREE Python cheat sheet: http://bit.ly/2Gp8...
I would personally - all of the syntax is the same for basic functions
using global here ew
so what i need use
time converter ?
"here"
Yes
jai hind boss
dude it trash
i know python
Yes
lol
ergh. The only real difference for me would be lack of ability using newer Typing sytnax
def foo() -> list[str] | none:
pass
either way its not something you gag at or act disgusted, its pretty handy
It seems you don't 🙂
ok ok ;/ i will not click
I am here
class variables 
what i use to make it globel and use it any where
arent you that lady from the hata server 🤔
For some constants mby
no in an async environment its good
Not necessarily for variables that change a lot
Oh wait, there is also another difference. I remember asyncio inbuilt has better features in newer python versions. In python 3.8 i think iwill be without functions like async_to_sync for easy launch of sync stuff in multithreading imitating async
Considering that discord.py is async stuff, i need better async support
I'll go with python 3.10 then.
nova got caught 👀
Why not
I've been using 3.10.5 with dpy master with no issues if that means anything
dude it small thing wy i need learn 1 hour for nothing tell me or don't chat ;/
As good as that sounds it could lead to some unexpected issues
it's literally FUNDAMENTAL to Python
to know how to handle variables
and you're right about the asyncio benefits: being able to use asyncio.to_thread instead of the ugly ass loop.run_in_executor thing is very convenient
i know how
it's not a little thing, it's the foundation of your python ability
i want to take input as hrs , how can i create a converter ?
built in library "datetime" or "time"
and maybe rule 5 👀
Check out pytimeparse library
I am a he.
Hi a he, I’ m enslo
sup
I’ m sorry, that was a horrible dad joke
True
plot twist you are a dad
plot twist yes i am
😳
oh, apologies. I seem to remember you getting banned and then flamed in the hata server for doing something 😅
also hi 👋
Ok
hi hi✌️
Is there a way to split fetchall into pieces.? I have 21 rows in my db right and i want to split them in 3 (10 + 10 + 1)
?
He tried
true
I tried
xd
and something else
wdym?
I have question
ohkay
I am making embed pages and i take data from db , fetch it and send it through embed. Cause i want every page to have 10 rows/values, it did fetchmany(10) and i want to have as many pages as the rows in the table. How can i make that?
you want 21 pages?
no xd i mean , i want the bot to detect how much data is in the table and separate it into embeds
by 10?
Yes i want every page to have 10 values but i want the bot by itself to detect how many pages to make
You’ll have to implement the logic yourself, there’s no automatic way to do it
Oh well...
!e py rows = 21 pages = rows // 10 + (rows % 10 != None) print(pages)
why would you define rows
@slate swan that's example
did I ping right person?
where's rows being used?
@silk fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
3
forgot to put rows into logic, just did 21 instead of it..
!createvc 1h or 1m or 1s
how can i get there times as input ?
also @slate swan do you somehow probably in some world know why my slash commands do not appear?
is there a missing access error in your terminal?
did you make sure that there are no illegal characters in your slash command name/parameters/description
yes, I checked at there were only english letters
@silk fulcrum master hel
im not hell
help 😳
@silk fulcrum show me your code
😳
idk I have all the reason in my gist and i sent you that so
im out of options
sadge :(
I'll give you a hand 🙂
Have session in he class scope. ```py
class ...:
session: aiohttp.ClientSession
sure..
Also add with_app_command=True inside the hybrid command
that didn't help with slash commands not appearing(
hidden is also not a valid kwarg unless you do something with the constructor.
does self.tree.sync work?
it's set to True by default
i guess?
Ummm. My bot suddenly stopped working
It does say that it's online
And it does the tasks.loop
check if it does
c = await tree.sync()
print(True if c else False)
False
Cool, what's the copy_global_to function doing?
idk
if you replace the copy_global_to with sync
then it isnt syncing anything 😔 rip
and await it
@silk fulcrum can I see the surrounding code to where you sync?
wdym?
uhm, this is setup_hook, if that's the code you want
async def setup_hook(self) -> None:
self.session = aiohttp.ClientSession()
# Hybrid commands set up
self.tree.copy_global_to(guild=discord.Object(id=980346257371455528))
await self.tree.sync()
for extension in initial_extensions:
try:
await self.load_extension(extension)
except Exception as e:
print(f'Couldn\'t load {extension}.', file=sys.stderr)
traceback.print_exc()```
And I get 0 error
do some debugging with print()
I went AFK for an hour, And the bot isn't working
It was great before I left
@crystal glen
yes?
Is this the first time you're running it for prolonged times?
Is it possible you haven't accounted for a certain situation which errors
ok master
Yes
Yay now it's working
that prooves another time that im 100000 times dumber than all peo...
it worrrksss
proves*
yes I gave you the answer almost more than 6 hours ago 
yayyy
now you trust me that Im dumb, nice I feel satisfied
13 year old poop cannot be smart
no, you're cute
🗿
oh wait you're 13, I sound like a pedophile nvm
LMAO
@grim oar moment
Guys i keep getting banned from using the API for too many requests and idk how to reduce it 😭
reduce your calls
boi what the hell boi🚔
Are you using repl.it to host your bot?
Atm yes, but I don’t use it for all my projects. It’s just easier to set up programs on it (fast prototyping)
That'll probably be the cause of your API bans
Could you explain why?
Per cluster in repl.it they share IPs among them
So since API Bans are IP based, if someone else got ratelimited
So do you
Ah okay
But let’s just say the api ban was because I did have too many request
How do I reduce that like I don’t really know what counts as a request if I’m being honest with you
Most if not all coroutine functions will be an API call
A common example is fetch vs get
get_channel is a regular function or more correctly termed a method (since it's bound to your client or guild)
fetch_channel is a coroutine function, you call it then await it
Awaiting usually signifies something as an API call since it usually is done to request
get_channel grabs from an in-memory cache, just a dictionary
And fetch_channel does a request to channels/:channel_id
Oh okay, what about listeners and such?
As in bot.listen?
Yeah
There is no ratelimit for those
bot.listen, bot.event and the a-like all work using gateway events
Ah okay that’s good
But the caveat comes from whats inside your event callbacks
Say you do 1 request in an on_message callback
Gotcha
Depending on how many messages are sent per it'll do a lot of requests
So keep that in mind when trying to reduce API requests
Yikes
Not hard just be conscious of what your doing, and you'll be fine
I’ll use if statements and such to limit and decide when I want to request something through message events
Sure, but you also don't have to be that afraid of using requests
Currently the GLOBAL ratelimit is set to 50/1s
So you can do 50 requests a second
I don't think your passing that amount rn I just think it's due to repl.it
Time to use asyncio.sleep 😎
Alright
Check if ctx.channel.id is same as the specific channel id
@bot.slash_command(name="register", description="Registers your server into the database")
@application_checks.has_permissions(administrator=True)
async def register(interaction):
servermembercount = len([member for member in interaction.guild.members])
id = interaction.guild.id
with open('guilds.json', 'a') as f:
json.dump(id, f, indent=4)
embed = nextcord.Embed(
title="Guild Registered!",
description=f"Your guild has been registered into the database!\n > **Server Owner:** {interaction.guild.owner.mention}`{interaction.guild.owner}`\n > **Server Members:** `{servermembercount}`",
color=0xffffff
)
embed.set_author(name=interaction.guild.name, icon_url=interaction.guild.icon.url)
await interaction.send(embed=embed, ephemeral=True)```
i created a random choice generator and want to have it run in discord by a text command, what information should i be looking into, to do this?
so far i can make my bot talk, but am struggling in finding information on having it run a normal python script lol
it doesn't need to do anything complicated, it just needs to be told something like "random" and then i want to run a script that has already been wrote and works, then display the results in discord channel
put {} as the content of file?
You add the random function within the script
that starts your bot
then i can have to bot just print the results?
you're saying that the script itself can run in the same script as the bot? then just tell the bot to print results?
I dont get the problem
If you pass the return of the random function into a message, something similar to
message.channel.send(f'{random_function_return}')
Do you just want a command?
A "script" is just a file, you can have multiple functions within a script, that can all use each other if need be
i'm using pycharm and i have never made anything outside of the main.py, are you saying that both can operate in the same? i'm not great at the terms, i am very new to this and just trying to help out a group i moderate for haha
Yes
thank you!
i dont know why i thought that would not work
i am really new to the bot stuff, had messed with kivy before and when i would try to add certain things in, it would mess it up, so i assumed the same.
declare a function like
async def random_generator():
-> do some things here
return something
and call it within the script using random_generator()
await then
Function that deletes a bots message?
I did not understand that conversation, but ok
!d discord.Message.delete
What's the qustion?
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/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
just been answered
Sweet

