#discord-bots
1 messages · Page 1096 of 1
I removed the import, only what to insert instead of it?
self.client
🥺
@commands.Cog.listener()
async def on_member_join(self, member: discord.Member):
channel = self.client.get_channel( 977252614498582538)
role = discord.utils.get ( member.guild.roles, id = 977252174964871258)
await member.add_roles (role)
await channel.send ( embed = discord.Embed (description = f"``{member.name}``, добро пожаловать на сервер", color = 0xffffff))
Did you bind the commands.Bot instance to your class?
def __init__(self, client: discord.Client):
self.client = client
But use commands.Bot instead
Yeah
@commands.Cog.listener()
async def __init__(self, member, client: discord.Client):
self.client = client
channel = self.client.get_channel( 977252614498582538)
role = discord.utils.get ( member.guild.roles, id = 977252174964871258)
await member.add_roles (role)
await channel.send ( embed = discord.Embed (description = f"``{member.name}``, добро пожаловать на сервер", color = 0xffffff))
😖
In your setup function you need to instantiate it with the commands.Bot instance
def setup(bot: commands.Bot):
bot.add_cog(mod(..., bot))
If 2.0, use the async version
Works, Works!!! You are so great at explaining everything. It's not the first time I've been here. Thanks
Thank you 😊
yes :troll:
show 
i recently switched to nextcord and i don't know how to send direct messages to only one user, in discord.py it was like this ```py
member = bot.get_user(The ID of user)
await member.send("Message")
is here a nextcord channel?
"doesn't work" doesn't really help us understand your issue. Are you getting any tracebacks? Did you just change from dpy to nextcord or did you change some code?
i changed form dpy to nextcord and the error is ```py
'NoneType' object has no attribute 'send'
get_user isn't finding the user that you've specified so it's returning None. You probably have some messed up intents or try using fetch_user
@client.event
async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
if getattr(ctx, 'handled', False):
return
if isinstance(error, commands.TooManyArguments):
await ctx.send('Too many arguments.')
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'Missing required argument `{error.param.name}`.')
elif (isinstance(error, commands.NotOwner) or isinstance(error, commands.MissingPermissions)):
await ctx.send('You do not have the required permissions to invoke this command.')
elif (isinstance(error, commands.CommandOnCooldown) or isinstance(error, commands.CheckFailure)):
await ctx.send(error)
elif isinstance(error, commands.BadArgument):
await ctx.send(f'Bad argument: {error}')
elif isinstance(error, commands.BotMissingPermissions):
await ctx.send('Oops! The bot does not have the required permissions to execute this command.')
log.error(f'{ctx.command.qualified_name} cannot be executed because the bot is missing the following permissions: {", ".join(error.list)}')
elif isinstance(error, commands.CommandInvokeError):
await ctx.send('Something went wrong internally!')
log.error(f'{ctx.command.qualified_name} failed to execute. {error.original.__class__.__name__}: {error.original}\n{"".join(traceback.format_tb(error.original.__traceback__))}')```
does this look fine? or do i need to handle any more errors?
oh and also do i need to put
return error``` after each if/elif?
nope
great
it looks ok, however I'd probably recommend either raising or printing out any other errors that don't get caught by the if statements
hello, im trying to do verificationn captcha, but it sends 2 messages and its very weird
this is my code:
https://paste.pythondiscord.com/unigowajih
Hi, we will not assist in projects that are trying to solve captchas. This falls under Rule 5
hmm, there are too many of them to handle, i did handle the ones which are used in my program
if you see any necessary missing, let me know please
well you don't seem to have a get_bank_data function
oh okay, my main problem is with the message content
You are trying to set up a user captcha verification through your bot? And not solving a captcha with your bot correct?
I mean, there's always gonna be that one exception that you did catch, so having some else statement there that just prints out the error so you don't miss it is gonna be quite useful in the long run
yes, so if the captcha is wrong it should send how many attempts you have left, and if its right it should give you a role, but it sends it twice
get_bank_data isn't defined in the line of your code
It could be seeing it's own messages
ii have a check for this
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.author.dm_channel
Thats not in the pastebin you sent earlier though
but why
well cause otherwise python has no clue whatget_bank_dataeven does
how do i define it
this is basic python, please learn some of the basic stuff before trying out more complicated stuff like anything discord-library-related
oh yeah it was one line above the first one in the paste bin
i accidentally left it out
Hmm. I'm not too sure to be honest
Any1 know where i can learn slash commands
oh, so do i go put
else:
print(error)```
after every if/elif?
yes
cool, thanks a bunch

lee quick question, can i make my bot send any red text which comes in console to a certain discord channel in form of a file? cause errors can be VERY long
i think its called stderr?
yeah its very weird
i have a feeling because of the while and something messes it up
I mean, error will just be the line of the actual error, not the whole traceback (e.g NameError: name 'a' is not defined) so I don't think it can get that long
oh okay so the error then, can i make my bot send it in a channel?
could you show the full code?
sure
how do i try catch all errors though
the whole command?
is there any common handling function?
wdym?
the part that matters
https://paste.pythondiscord.com/jumewewiba its only that
like all the red text in the console, gets dumped to a discord channel, regardless of its being a TypeError or CommandNotFound or BadArguements are whatsoever
just whatever is red
its so weird because it works now, but when i do it again it doesnt work anymore
before you check what the error type is, send it to the channel
I don't think it's your issue, but I hope you're importing TimeoutError from asyncio?
oh no its from python
wait_for doesn't raise TimeoutError, it raises asyncio.TimeoutError
oh okay thank you
just use http methods and send messages whenever an error is raised by using send_message http method in the on_command_error event
why?
why not?
just get the channel and send it there? no need to use http methods?
just trying to save up api calls in case get_channel returns None
i mean i am not gonna delete the logging channel ever
so i doubt i will be getting None
it's 1 less API call ._. huh, well I mean they could just DM the error 🤷
why even get the object...using http methods is lesser work
is there any reason why you're doing it that way? why are you using dictionaries instead of a simple variable that keeps track of the attempts?
Would love it if Danny or a contrib comes here and sees people suggesting others to use http methods
he already got mad at me once for doing that in the dpy server
lmao
dpy server- his territory
python server- not his territory
how can i input more then one word
like !say lksdfjl;askjf;laskjdf;laskjdf;laskjdf;laskjfd
yestellmehow
*, message
I mean, common sense says
channel = bot.get_channel(id) or await bot.fetch_channel(id)
await channel.send(...)
''' or '''
from discord import http
await bot.http.send_message(channel_id, http.handle_message_parameters(content="uwu"))
inoknowshttp
ok
those are some nice function names
Thanks for deleting that Savvy
i gotchu my guy
i have a variable, the dicts are from pymongo
ay i am asking how to get that "content" over there
and the timeouterror still doesnt trigger
except asyncio.TimeoutError:
await ctx.author.send("Your Captcha expired. You will be kicked.")
the argument you pass in to the on_command_error that serves as the error raised
async def on_command_error(ctx, error): http_method(content=error)
look
please just refer to it as an error/exception, saying red text is kind of ambiguous
i am saying not just the command errors, but ALL errors
lmao okay
well, use the on_error event then
!d discord.on_error
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.10)").
If you want exception to propagate out of the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") class you can define an `on_error` handler consisting of a single empty [raise statement](https://docs.python.org/3/reference/simple_stmts.html#raise "(in Python v3.10)"). Exceptions raised by `on_error` will not be handled in any way by [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
this is still a discord error event
Thx
I want make a command that allowed me to set the channel where the bot would send messages. For example: .defineSuggestions #channel (it would define a specific channel for the suggestions) and then .sendSuggest (suggestion) and it would send the suggestion in that channel. Any suggest?
is mongodb down?
or maybe rate limits
or a website blocking the program
or failed to fetch some data
all the damned possible errors
if the website blocks the program then how's it gonna send-
well, idk, do you have some other functions that could return None?
which arent commands probably
and do you call those functions within commands
and I think on_command_error makes it possible to pretty much handle every error
maybe fetch json data
and is that outside a command?
yeah its on initialization
on_error covers all exceptions though? even those raised outside of commands?
ohh peace then
I hate trying to help in this channel anymore now
do or do not, there is no try 
you're in the java server?
🔫
maybe
@bot.command() async def add(ctx): if ctx.author.id not in dev: await ctx.send("Contact staff to buy premium") else: if ctx.author.id not in premium: premium.append(ctx.author.id) await ctx.send("Premium **SUCCESSFULLY** enabled")
any who can help
import traceback
@client.event
async def on_error(event, *args, **kwargs):
channel = client.get_channel(channel_id)
logging.warning(traceback.format_exc())
await channel.send("go open the file and check error wazacxauhz")```cool?
what's the problem
send the traceback
and i cant use if ctx.author.id not in premium:
why not
because code didnt append user id to list
are you getting an error?
no
sure
is it sending the message?
how do i send the error instead of go open the file and check error wazacxauhz ? that would be a lot cooler
ye but didnt add user
which one is it sending
Premium SUCCESSFULLY enabled
you mean something like this?
exc = traceback.format_exc()
logging.warn(exc)
await channel.send(exc)
yeah! thanks
if ctx.author.id not in premium: is this condition true?
add a debug print statement under this line so we see if it's true or not
ye
but its didnt work
are you sure it's true?
Are you sure it's not being appended?
print the list after that line. Is it still empty?
ye
For some reason that always returned None for me, so I am thinking of doing smth like
import io
import contextlib
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
raise error
All this in the error handler
okay i did this
@client.event
async def on_error(event, *args, **kwargs):
channel = client.get_channel(977441403229593643)
exc = traceback.format_exc()
logging.warning(exc)
await channel.send(exc)```
i got this when i did a wrong command on purpose
but nothing in the discord channel
you might have another error handler which handles this error before on_error
nope
also, why are you taking *args, **kwargs? 
no idea just thought i should take
would you mind sharing your whole code? you don't have to paste every command
!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.
tbf I've never really used format_exc, I always prefer to use format_exception. I just checked the docs and return type so in my mind it should kinda work ig (also never really had any circumstances in which I'd need to use on_error) 😅
i do not have any error handlers yet
you just said you have on_error
besides that DUH

^^
no no no no i need all errors not just command errors
sure just for tests
okay
what other things could error though?
tasks have error handlers and just use try/except for cog loading?
!d discord.on_error
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.10)").
If you want exception to propagate out of the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") class you can define an `on_error` handler consisting of a single empty [raise statement](https://docs.python.org/3/reference/simple_stmts.html#raise "(in Python v3.10)"). Exceptions raised by `on_error` will not be handled in any way by [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
¯\_(ツ)_/¯
@heady sluice yeah so it works w on_command_error so is the test done?
what to do for on_error
yes
seems like on_error doesn't handle command exceptions
or just this specific one
dunno
cause
thanks it works !
you can only dm the visible members anyways...
you can just fetch the user object from the api, no?
how do i send a message to a specific channel again
on message event or command?
on member join
bot.get_channel(id) or bot.fetch_channel(id) to get the channel object and then send using send attribute
first get the channel and safe it in a variable. Like: channel = bot.get_channel(id). Then await channel.send(‘message’)
ok thanks
try the first befause i’m not that god
I'm not that good also 
neither works
no error messages
Do you have intents enabled?
how do i trigger TooManyArguments?
raise commands.TooManyArguments(...)
no
i tried putting an extra arg in the command but that didnt work
wdym?
10.06 20:28:33 [Bot] File "/main.py", line 6, in <module>
10.06 20:28:33 [Bot] import discord
10.06 20:28:33 [Bot] ModuleNotFoundError: No module named 'discord'
how do I fix this? I'm going through pebblehost and I've got everything in requirements
consider command
async def pokestat(ctx: commands.Context, pokemon: str):```
i did pokestat xyz xyz xyz
so that should trigger it right? does nothing
it triggers command invoke error for some reason
uh
i mean, when i do pokestat xyz xyz xyz, it just considers pokestat xyz and ignore the latter text
so idk how to trigger too many arguments
when an exception is raised on command invoke, it gets wrapped in CommandInvokeError before being thrown to an error handler. iirc CommandInvokeError has an original attribute with the actual exception
ImportError: cannot import name 'app_commands' from 'discord' (/.local/lib/python3.9/site-packages/discord/__init__.py)
Did you install discord.py from pip?
yeah I've got that installed, It's interesting cuz I have the bot working on a different machine but wasn't actually being hosted. I'm going through pebblehost atm and I've got everything in their requirements
10.06 21:02:52 [PebbleHost Loader] Installing discord.py
It's discord.py 1.7.3 on pip you need to install from GitHub to get the app_commands
python -m pip install -U git+https://github.com/Rapptz/discord.py
I don't think I can run commands through them they said to go through 'https://pypi.org/project/discord.py/'
well through the site but that's the one I'm assuming is the correct one
discord
discord.py
asyncpg
asyncio
json
requests
http
numpy
tweepy
base64
random
don't think all that is necessary but I just added everything into their requirements.txt so really unsure what I'm missing/doing wrong
It should be member.edit not member.username
guys can anyone help me attach ffmpeg-static to PATH
how can i made it that i have to ping inuser in a command?
i'm using it to make a discord music bot
Linux?
no windows
Install ffmpeg.exe and get the path lol
how exactly lol
Uh, go to the site to download, then copy the path, then define the location inside the file
i do not understand
what do i copy
The path
I don't think you need it in the path
i do
However I am sure there is plenty of information on YouTube and internet
I'm not good at adding stuff to PATH, it's disgusting
please provide a yt link or something that could help
In this video, I'll show you how to install FFmpeg codex on Windows 10 and add it to system path so that you can run the commands easily.
"FFmpeg is the leading multimedia framework, able to decode, encode, transcode, mux, demux, stream, filter and play pretty much anything that humans and machines have created."
Download Link
https://ffmpeg.o...
Why add to PATH when you can just parse the executable path to executable param 🤨
wut
!d discord.FFmpegPCMAudio
class discord.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)```
An audio source from FFmpeg (or AVConv).
This launches a sub-process to a specific input file given.
Warning
You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.
bruh i'm a beginner i do not understand any of this shit
And you just copypaste code?
no
Good
learn things here and there
and then choose the perfect code
use it and solve some errors
Just download the ffmpeg executable, put it into your project folder and set the executable param of your audio source constructor to ./ffmpeg.exe
"Choose the perfect code" means copypaste it or write own based on it?
i mean the perfect line of code
Ok got it, right method
this worked thank you @rocky trench
i've dealing with this for a day and a half
i also need help making a loop code
here is main.py ```import discord
from discord.ext import commands
import music
cogs = [music]
client = commands.Bot(command_prefix='?', intents = discord.Intents.all())
for i in range(len(cogs)):
cogs[i].setup(client)
client.run('token')```
here is music.py ```import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def init(self, client):
self.client = client
@commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel!")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)
@commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format':"bestaudio"}
vc = ctx.voice_client
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
@commands.command()
async def pause(self,ctx):
await ctx.voice_client.pause()
await ctx.channel.send("Paused ⏸")
@commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.channel.send("resume ⏯")
def setup(client):
client.add_cog(music(client))```
is it just like the commands pause and resume
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
could you listen on the leave channel event and check if it's the bot that left?
erm in discord py 2.0 it got changed from icon_url to something else
I want to say icon.url? I can't quite remember
check the docs, it might have been changed there
something like
async def on_voice_state_update(self, member, before, after):
ive got an example in my old discord bot (the code is pretty bad throughout it but it works) on discord.py 1.7.3, but i dont believe the stuff you need has changed much
https://github.com/MrRazamataz/old-RazBot/blob/main/cogs/music.py#L279
Yep
import discord
from discord import app_commands
from discord.ext import commands
from discord import member
from discord.ext.commands import has_permissions, MissingPermissions
import os
class aclient(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id = here_goes_guild_id))
self.synced = True
print(f'Logged in as {self.user}.')
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(name="help", description='Help command.', guild = discord.Object(id = here_goes_guild_id))
async def self(interaction: discord.Interaction):
embed = discord.Embed(name="help", color=0x03f4fc)
embed.add_field(name='**Example**', value="Hi!.", inline=False)
embed.add_field(name='**Example**', value="Hello!.", inline=False)
await interaction.response.send_message(embed=embed)
@tree.command(name="example2", description='Example command.', guild = discord.Object(id = here_goes_guild_id))
async def self(interaction: discord.Interaction):
embed = discord.Embed(color=0x03f4fc)
embed.add_field(name='**Example**', value="Example!", inline=False)
await interaction.response.send_message(embed=embed)
@tree.command(name='example3', description='Example command.', guild = discord.Object(id = here_goes_guild_id))
async def self(interaction: discord.Interaction):
embed = discord.Embed(color=0x03f4fc)
embed.add_field(name = "**Example**", value="Example!", inline=False)
await interaction.response.send_message(embed=embed)```
why commands don't work
saying "commands don't work" doesn't really help, could you be more specific?
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 650, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "c:\Users\USER\Desktop\PC\whocares\main.py", line 26, in self
embed = discord.Embed(name="Help command", color=0x03f4fc)
TypeError: Embed.__init__() got an unexpected keyword argument 'name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1157, in call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 675, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 664, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'name'```
that happens when i try /help
every other command is working
title, not name
is this where I can ask discord.py related questions?
how
async def raid(ctx, arg):
if arg == 'battle':
await asyncio.sleep(5)
await ctx.send("message")
return
#I want this to have a cooldowon so that it can only be used once every minute
#I also want the bot to reset the once every minute cooldown if it detects a message that says "you are not in a raid"
if arg == 'surrender':
await ctx.send('surrender message')
return
on both of them?
could you explain?
I can't understand a thing lol
I copied the command example
the commands.command
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 384, in _run_event
await coro(*args, **kwargs)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1168, in on_message
await self.process_commands(message)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1165, in process_commands
await self.invoke(ctx)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1132, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 552, in dispatch_error
await injected(cog, ctx, error)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 172, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: [Errno 9] Bad file descriptor``` do one of u know how fix this?
the invoking part
Code please?
may I dm you?
thats the thing idk
The part causing the error
bc i dont even have a bot.py file
or core.py
shottas.py is my main file
but i am using cogs
How about this, can you post the full traceback?
That usually tells us in which file and in what line the issue is happening
OSError: [Errno 9] Bad file descriptor
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 182, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\cogs\ac.py", line 22, in punishment
data = getConfig(ctx.guild.id)
File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\Tools\utils.py", line 33, in getConfig
updateConfig(guildID, defaultConfig)
File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\Tools\utils.py", line 44, in updateConfig
config.write(newdata)
OSError: [Errno 9] Bad file descriptor
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1128, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 899, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 191, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: [Errno 9] Bad file descriptor
During handling of the above exception, another exception occurred:
OSError: [Errno 9] Bad file descriptor
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 166, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\cogs\ac.py", line 75, in punishment_error
data = getConfig(ctx.guild.id)
File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\Tools\utils.py", line 33, in getConfig
updateConfig(guildID, defaultConfig)
File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\Tools\utils.py", line 44, in updateConfig
config.write(newdata)
OSError: [Errno 9] Bad file descriptor
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 384, in _run_event
await coro(*args, **kwargs)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1168, in on_message
await self.process_commands(message)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1165, in process_commands
await self.invoke(ctx)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1132, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 552, in dispatch_error
await injected(cog, ctx, error)
File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 172, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: [Errno 9] Bad file descriptor```
Can you paste utils.py?
yea
Hey @slate swan!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
it's not a public bot it's a bot for me and my friends
Regardless of the usecase we can't help you here
why exactly?
Because it's against rule 5
Might be a write issue, are you sure the file is valid?
the TOS apply if i am making a public bot
oh yea naw they can not help u they can get sued and termed
its not about u
Not necessarily
wym valid?
i havent touched that file in so long
Does the file actually exist?
how is youtube gonna sue them for something private and not public
i mean its there and shows in files so i think
can i get help there?
No
then why is it important to join
Hi. I have some working code but I'd like to write it differently and I'm not sure that I can. Here's what I have:
CancelButton = disnake.ui.button(custom_id = "cancelitem", label="Cancel", style=disnake.ButtonStyle.grey)
ConfirmButton = disnake.ui.button(custom_id = "confirmitem", label="Confirm", style=disnake.ButtonStyle.green)
class UI(disnake.ui.View):
def __init__(self):
super().__init__()
self.value = None
@CancelButton
async def cancel(self, input, inter):
self.value = 0
self.stop()
@ConfirmButton
async def confirm(self, input, inter):
self.value = 1
self.stop()
and I'd like to move the async def bits up to where the buttons are defined
is that possible? how would I do it?
python >> js my opinion else truth
you would be right if js can not create amazing 3d games like minecraft
It might be, but if you're looking to keep things together (I assume so, since you're asking how to move it up) you might want to just decorate the function normally without using your @CancelButton and @ConfirmButton
Other than that though, th e code is fine
lmao if its games ill just do it in c++ my better lang anyways i only learned py for cord plus i wanna learn them all
better lang does not mean better skills at coding
I would like to reuse the UI elements and functions in multiple different UI Views without having to rewrite it each time
wat i said my better lang lmao
meaning i have better skills in scripting in c++ then i do in python
Ah, I see. In that case you might want to just subclass disnake.ui.Button
it might be but there also might be a few functions that you didn't learn
That way you keep everything in one class, and reuse it whenever you'd like
There is no such thing as a "better language"
that's probably a great idea but unfortunately I have no clue what you mean
js is java script
exactly all opinion
"c++ is my better lang" is like "baseball is my better sport" aka "I am better at it" not "it is better"
class MyCustomButton(discord.ui.Button):
def __init__(self):
super().__init__(...) # construct your button as usual
async def callback(...):
...
You can create that button easily like: MyCustomButton()
Reuse as much as you'd like
didn't know that
r u ok? like honestly bc if ur saying that js is better for game dev ur smokin dick
c++ is better
but hey not everyone is perfect
bruh you can't read lmao
Let's take it down a notch please
that's not at all what I'm saying
oh hello there mr smoking pussy
Can we not please, and get back on topic?
im smoking this cart
I'd rather not have to call in the moderators
bruh it's not a fight
Seems like it and is also wildly off topic
i agree but this member is basically saying "if you have a different oppinion than mine then eat shit"
Ok, how about let's not do that again and move on
everyone has different opinions and every one should respect that
ayy
how would I add that to the UI then?
Inside your view:
class MyView(discord.ui.View):
def __init__(self):
super().__init__(...)
self.add_item(MyCustomButton(...))
You can use discord.VoiceClient.is_connected() to check if you're connected
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected Item not <class 'abc.ABCMeta'>
Can i see the code?
here's all of it:
import disnake
from disnake.ext import commands
class CancelButton(disnake.ui.Button):
def __init__(self, null):
super().__init__(label="Cancel", style=disnake.ButtonStyle.grey) # construct your button as usual
async def cancel(self, input, inter):
self.value = 0
self.stop()
#await inter.response.send_message("Cancelled!")
ConfirmButton = disnake.ui.button(custom_id = "confirmitem", label="Confirm", style=disnake.ButtonStyle.green)
class UI(disnake.ui.View):
def __init__(self):
super().__init__()
self.value = None
self.add_item(CancelButton)
@ConfirmButton
async def confirm(self, input, inter):
self.value = 1
self.stop()
class Ask(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def ask(inter):
"""Asks the user a question to confirm something."""
layout = UI()
await inter.send("Do you want to continue?", view=layout, ephemeral = True)
await layout.wait()
if layout.value == None:
await inter.edit_original_message("Timed out", view=None)
elif layout.value == 0:
await inter.edit_original_message("Cancelled", view=None)
elif layout.value == 1:
await inter.edit_original_message("Confirmed", view=None)
def setup(bot):
bot.add_cog(Ask(bot))
?
thats fine
Hey got a dpy 2.0 question here: so I'm currently creating ext.commands separately from app_commands and I think it would be beneficial to move to hybrid commands.
- is there any restrictions what args hybrid commands can take (e,g. will they accept models/forms?)
- does the bot will create the default help command with hybrid commands (with or without a slash help command)
you have to name the special method as callback not cancel (see robin's example),
then you have to call the class too while adding it to the view
and the callback method takes, self, interaction: discord.Interaction
how does this work when I have multiple methods?
you can't
nor does it make any sense
so then this solution doesn't work for me.
what's the issue though
^
I want to have a button and an action that I can add to as many UI Views as I want without having to rewrite them
the naming conventions ....right now, input represents the current instance (Button) which is a bit off the way isnt it, ps I dont think using those kind of decorators (even if they work idk) is a good practice anyways
just do what robin said then
didn't you just say this only works once (with one button's action)?
huh?
I never said anything like that, you might have misunderstood me
probably
well, about the first part, you create a callback function for a command just the way you do for slash (app) commands, so yes, it pretty much does support modals
and about the second part, it does give you a prefix help command, I'm not really sure about the slash help
should I give a proper example for a reusable button, I dont mind
Im on phone so I might be slow but sure
Okay thanks for the info.
class ReButton(discord.ui.button):
def __init__(self):
super().__init__(label="uwu button", style=discord.ButtonStyle.blue)
async def callback(self, inter: discord.Interaction, button: discord.ui.Button):
await inter.response.send_message("you clicked me uwu", ephemeral=True)
#adding the button object to a view class
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=...)
self.add_item(ReButton())
@karmic marsh in this case, you can add ReButton to as many views as you want, and the callback method is the logic, in essence, the actions to be performed when the button receives an input
!d discord.VoiceClient.is_connected
is_connected()```
Indicates if the voice client is connected to voice.
you can also do guild.me.voice
this is very nearly what I need
(it's surprisingly close to what I had too)
I'm just having one issue
self.value = 0
#and
self.stop()
no longer point to the parent UI View
ofc
right
I just don't know what I need to change self to
or if that's no longer possible
hm, just declare a var fe self.par_view = view in the __init__
and do self.par_view.stop()
and when you add the button to the view class
self.add_item(ReButton(self))
pass in the instance of the View class using self
Now I probably have a broken humour but, why are commands declared in CommandTree using command and not leaf since leaves make food for the plant
tree = CommandTree(client)
@tree.leaf()
async def uwu(): ...```
okay i feel bad saying that now
my humour is so fucked up

Leaves have a different meaning in trees in the context of programming
It’s be a bit misleading to call commands leaves
boomer robin 😔
binary search trees do that to you
how would i go about writing in a func (not a command) which checks if a user has a role before its called? same effect as if it were a command, but written as a func
We had quizlets with BST terminology like leaves, nodes, heads, and the formulas for calculating them in comp sci
the reason i dont want as a command is so that it cant be called just anywhere; only within a certain part of my code
Maybe checks are a better way to do that?
you want a decorator check or a function check?
They can be reused anywhere
well, functions also are created for the same purpose, aren't they
True a check is a basically a function
basically im trying to make it so only people w x role are able to use this function which will change a variable in my code
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
It’s so common that there’s a shortcut check for it
can i put this within the func tho ?
i was under the impression commands can only be used outside of a func
Just decorate the commands you want with that decorator
I assume you don’t want every single command to be locked to those with that role
no; im tryin to set up sleep in parts of my code, and i want only the devs to be able to turn em off
so prob single use ye
Yah so just decorate it with the has role check
alr
makes me realise that tree.branch is a good one for group commands.
I'm sorry, I still don't quite know what you mean
yo wait I might have gotten it
alright, it's working
hey in fact, I can simplify a lot of the other logic too with this parent_property method
alright, this works beautifully
here's the code:
import disnake
from disnake.ext import commands
class CancelButton(disnake.ui.Button):
def __init__(self, view, inter):
self.par_view = view
self.par_inter = inter
super().__init__(label="Cancel", style=disnake.ButtonStyle.grey)
async def callback(self,inter):
await self.par_inter.edit_original_message("Cancelled", view=None)
self.par_view.stop()
class ConfirmButton(disnake.ui.Button):
def __init__(self, view, inter):
self.par_view = view
self.par_inter = inter
super().__init__(label="Confirm", style=disnake.ButtonStyle.green)
async def callback(self,inter):
await self.par_inter.edit_original_message("Confirmed", view=None)
self.par_view.stop()
class UI(disnake.ui.View):
def __init__(self, inter):
super().__init__()
self.add_item(CancelButton(self, inter))
self.add_item(ConfirmButton(self, inter))
class Ask(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.slash_command()
async def ask(inter):
"""Asks the user a question."""
layout = UI(inter)
await inter.send("Do you want to continue?", view=layout, ephemeral = True)
timeout = await layout.wait()
if timeout:
await inter.edit_original_message("Timed out", view=None)
def setup(bot):
bot.add_cog(Ask(bot))
@tree.command(name="kick", description='Kicks people from the server.', guild = discord.Object(id = here_goes_guild_id))
async def self(ctx, member : discord.Member, *, interaction: discord.Interaction, reason=None):
await ctx.member.send(f"You were kicked for: {reason}")
await member.kick(reason=reason)
embed = discord.Embed(title = "A user was kicked!", color=0x03f4fc)
embed.add_field(name="**Kicked user:**", value=f"User {member.mention} was kicked from the server.")
await interaction.response.send_message(embed=embed)```
this doesn't seem to work
File "c:\Users\USER\Desktop\bots\whocares.py", line 55, in <module>
async def self(ctx, member : discord.Member, *, interaction: discord.Interaction, reason=None):
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 878, in decorator
command = Command(
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 523, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 383, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 700, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 659, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>```
because you can't have an interaction as a command argument.
could you explain? i don't really get it lol
meaning async def self(interaction, member, *, reason)
what
app commands don't have CTX
slash command uses interaction as their ctx
they are both 2 different things
and only 1 can be used
in slash we use interaction
and in prefix commands we use ctx
do you understand what you wrote there?
what was that method name that get called on timeout?
any fix for that?
targetID is none
async def self
you mean what event? its on_member_update iirc
ye
ctx is just a naming convention, and is kinda vague of you to say that
i mean on view
its a kick-yourself command
on_timeout
but....why would anyone name it self...instead of defining the name in the command deco
or actually not, they describe it as that but do something else inside the function
ye that thanks :D
since it's a reserved keyword
it takes interaction btw iirc
its not a classmethod so doesn't matter, even if it was it won't
anyone else?
ye ik
but...isn't self a reserved keyword...
nope
!d discord.ui.View.on_timeout
await on_timeout()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when a view’s timeout elapses without being explicitly stopped.
no, thats just a convention
my bad then
convention yes
how to find degree and cardinality of SQL table ik degree is number of columns is cardinality rows?
its like on_ready which gets called internally or you can just use the coro and pass the coro obj iirc
cardinality is that
thx just being sure
not sure ab degrees
d.py slash commands do
google says yes too lol
Context != interaction
Correct
they have interaction ryt
hybrid commands
they use both, actually
some libs call it InteractionContext or something along the lines
you get parameter for both?
no its just one
its just class naming
iirc pycord does it idk
i remember pycord doing that, its like a mix of inter and ctx
Here’s an example of a slash command:
@bot.slash_command(description="Responds with 'World'")
async def hello(inter):
await inter.response.send_message("World")```
yea looks like
yeah 😭
ApplicationCommandInteraction
AppCmdInter works too ( its an alias )
oh xD
@slate swan
okay
disnake/interactions/application_command.py lines 518 to 525
# People asked about shorter aliases, let's see which one catches on the most
CommandInteraction = ApplicationCommandInteraction
CmdInteraction = ApplicationCommandInteraction
CommandInter = ApplicationCommandInteraction
CmdInter = ApplicationCommandInteraction
AppCommandInteraction = ApplicationCommandInteraction
AppCommandInter = ApplicationCommandInteraction
AppCmdInter = ApplicationCommandInteraction```
its in state.py if youre interested
👍
the ConnectionState class acts pretty much like the cache manager for discord.py lol
Current examples are slash commands, user commands and message commands.
huh i didnt know about those others
pretty much, ive seen some methods that use the ConnectionState class for accessing cached objs
message commands are basically the traditional @commands.command commands, user commands are context commands which you can see by right clicking on a message
or a user too iirc
can you make custom user commands ?
all of them do
Yes
yes
such wow
why am i missing brackets😭
is there markdown there lmao
ur not callable
😳
wait
lmao. gotta try smth now
yeah, they even allow bold and italics too iirc
never knew they used markdown for it
maybe some dont ??
weird
okay... you've got to tell me if this works lmao
same
can you click it?
nope
hmm... okay, neat
thats hilarious
its discord so...
that's amazing
Not really
i feel like thats kinda idk useless or over the top over not using it
ʰᵉˡˡᵒ ʷᵒʳˡᵈ
bro
what did you type
thats some text in superscript ig?
i typed ʰᵉˡˡᵒ ʷᵒʳˡᵈ
!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.
Thx
!charinfo ʰᵉˡˡᵒ ʷᵒʳˡᵈ
\u02b0 : MODIFIER LETTER SMALL H - ʰ
\u1d49 : MODIFIER LETTER SMALL E - ᵉ
\u02e1 : MODIFIER LETTER SMALL L - ˡ
\u02e1 : MODIFIER LETTER SMALL L - ˡ
\u1d52 : MODIFIER LETTER SMALL O - ᵒ
\u0020 : SPACE -
\u02b7 : MODIFIER LETTER SMALL W - ʷ
\u1d52 : MODIFIER LETTER SMALL O - ᵒ
\u02b3 : MODIFIER LETTER SMALL R - ʳ
\u02e1 : MODIFIER LETTER SMALL L - ˡ
\u02b0\u1d49\u02e1\u02e1\u1d52\u0020\u02b7\u1d52\u02b3\u02e1\u1d48
Yep, one sec 😄
I'm unsure, sometimes it works, sometimes it doesn't.
It will say "Name is thinking..."
Then sometimes it'll just say it failed immediately.
What happens if you remove the defer?
It's still a 50/50 last I checked.
I changed a few things but I can check one more time
It's random when it wants to work, I might've messed something up
It wouldn't affect it unless it's doing something blocking afaik
Unless, can you not do that with followup.send?
yes.
Music bots extract audio from youtube through youtube_dl which in return breaches youtube's TOS. So, abiding to rule 4, we certainly cannot help anyone related to audio extraction
!ytdl to see why it breaches the TOS
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
then why are there so many music bots??
your question should be why are so many big music bots are now becoming unfunctional
plus, can't we use spotify?
hydra.....
hydra doesn't support any sounds from YouTube anymore
they are making themselves limited
No
Spotify haven't taken down any bot for using their API for playing music yet but they have similar ToS, all services do
https://developers.soundcloud.com/docs/api/guide
Use SoundCloud API
these song companies buy these albums why would they let others extract and download for free
They allow streaming music as long as u follow their ToS
so basically, we can use spotify, right?
u can even use ytdl but we wont provide help for either
no
You just helped him by telling Right
Improper use. Do not improperly access, alter or store the Spotify Service or Spotify Content, including
using any robot, spider, site search/retrieval application, or other tool to retrieve, duplicate, or index any portion of the Spotify Service or Spotify Content (which includes playlist data) or collect information about Spotify users for any unauthorized purpose;
nope nvm me
Soundcloud allows streaming music bruv
SoundCloud allows you to use its api freely, just don't download the songs, cache them instead
Yes
whos gonna download them anyways lol
Indeed
just listen from spotify discord isnt even a legit music streaming software
I back him. If u got Spotify, why even use a VC lol
Instead of sitting in the VC and listening to song, go touch grass
unexpected keyword argument
The view kwarg is in send() method
view is a kwarg in send
def pi(x:str,y:int):
return x*y
@spi.command()
async def ping(ctx,x:str,y:int):
pong=pi(x,y)
await ctx.send(pong)
basically i want it to be a ping machine but it only sends the number of pings in one message
i want to send string*int but each time the result in different line
can someone help?
infact i do touch grass
but basically you guys are telling, your not gonna help me make the music bot, right?
someone help with mine atleast 😭
u could just do for i in range(y): await ctx.send(x)
Yup
basically if you input .ping apple 3, you want
apple
apple
apple?
YES.
each time diff ping to the person
use a for loop
!e ```py
def foo(x, y):
print((x+"\n")*y)
foo("apple", 3)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | apple
002 | apple
003 | apple
"\n".join(string*number)
that will send the whole thing in one message just with new lines tho
he wanted like 3 pings ig
Weird
wrong
i mean wouldn't it send only 1 ping but with diff line
Then Asher is correct
@dim sentinel
Just realized, yea
for _ in range(y): await ctx.send(...) but this will get rate limited
then you gotta use a for loop as ryuga said
is it so hard to read the first answer
roger
🫂
lmao
thats why you ping them while answering when the chat is active
is it possible to have more than 25 option choices?
@spi.command()
async def ping(ctx,x:str,y:int):
i in range(y)
await ctx.send(x)
``` it says i is not defined, I am sure i am doing something wrong here
ah that sucks, i was trying to pass through 32 options
why tf?
different teams
32 teams...
@paper sluice can ye help? if ye don't mind?
how would that work?
sorry for the ping
i just wanted a nicer way for them to input which team
smh guy still cant scroll up and read
I'd just do py async def foo(inter, team, value): ...
and lower chances of messing up
just divide the 32 teams to like 4 categories abcd and display
slash commands have choices too, so they won't be able to choose any invalid team
u didnt use the for keyword 😔 (https://www.programiz.com/python-programming/for-loop)
ofcourse
i mean autocomplete is not even important when discord gives a better option called choices
so they'll never be able to use any invalid team
wym
only the teams you allow will be allowed to input in that field
u are not using slash commands?
like in thise option i have, the choices come up automatically
in case someone enters an invalid one, the get an error on their side
so i should always opt to use option choices because it eliminates error?
for things where it has to match a value
yep that would be more Efficient than having 32 options
ok, i will probably split my choices into groups of 4 then
omg
so sorry to even trigger you there
my bad
Also am i gonna get rate limited now 😃
for this spam
yeah if u cross a certain threshold of y
what do you think would be the limit?
oh then it's gonna be fine
it's one ping per sec
or more than that
it's definately not 25 pings per sec
All bots can make up to 50 requests per second to our API. This is independent of any individual rate limit on a route. If your bot gets big enough, based on its functionality, it may be impossible to stay below 50 requests per second during normal operations.
the bot's only for 1 server for now, because of my lack of knowledge and resources atm
so it's not gonna get ratelimited right?
@discord.ui.button(label='Verify', style=discord.ButtonStyle.green)
async def callback(self, interaction: discord.Interaction, button: discord.ui.Button):
name = 985055853096886283
member = interaction.user
role = discord.utils.get(member.guild.roles, id=name)
await member.add_roles(member, role)
await interaction.response.send_message(embed = discord.Embed(f"Welcome! {interaction.user.name}, you have been granted {role.name} role!", color = discord.Colour.green))
self.value = True
self.stop()```
Error: Unknown role
Assigns role on interaction
omg, really???
yes
woah
role is None
https://top.gg/tag/music see this website
oh nvm, role is fine, interaction.user returns a User object (use interaction.member instead)
ok
i can't have optionchoices inside of the command?
i want it to display different options if you input specific groups
groops = [
OptionChoice(name = "A", value = "A"),
OptionChoice(name = "B", value = "B"),
OptionChoice(name = "C", value = "C"),
OptionChoice(name = "D", value = "D"),
OptionChoice(name = "E", value = "E"),
OptionChoice(name = "F", value = "F"),
OptionChoice(name = "G", value = "G"),
OptionChoice(name = "H", value = "H"),
]
@bot.slash_command(description = "Change teams for user")
@commands.has_role("Captain")
async def team(ctx, player: discord.User, team: discord.Option(str, choices=choose), group: discord.Option(str, choices=groops), tmz: str):
if group == 'A':
choose = [
OptionChoice(name = "Tokyo Fart Sniffers", value = "Tokyo Fart Sniffers"),
OptionChoice(name = "Robstown Somethings", value = "Robstown Somethings"),
OptionChoice(name = "Baltimore Bughas", value = "Baltimore Bughas"),
OptionChoice(name = "London BC", value = "London BC")
]
elif group == 'B':
choose = [
OptionChoice(name = "Neko Cavaliers", value = "Neko Cavaliers"),
OptionChoice(name = "Xinzhou Warriors", value = "Xinzhou Warriors"),
OptionChoice(name = "Kyoto Kings", value = "Kyoto Kings"),
OptionChoice(name = "Charlotte Stingers", value = "Charlotte Stingers")
]
for example?
How to add multiple emojis?
where?
finally done verification with GitHub student🎉
In guild bro
Congrats!
thx
i think it was something like create_custom_emoji
Not single*
I wanted that if there is mentioned 2-3-4 emoji then it adds them
use a for loop and add them
Any other options?
nope
In discord.PartialEmoji How To use from_str method? @slate swan
!d discord.PartialEmoji
class discord.PartialEmoji```
Represents a “partial” emoji.
This model will be given in two scenarios:
• “Raw” data events such as [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add")
• Custom emoji that the bot cannot see from e.g. [`Message.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.reactions "discord.Message.reactions")...
classmethod from_str(value)```
Converts a Discord string representation of an emoji to a [`PartialEmoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialEmoji "discord.PartialEmoji").
The formats accepted are...
I believe like this
emoji = PartialEmoji.from_str(":bruh:") # idk if I wrote the form correctly, prolly not```
PartialEmoji Is Not Defined
Do some experiments and see what kind of emojis you can convert
You need to import it bro
?how
from discord import PartialEmoji
# OR
import discord
discord.PartialEmoji```
You would better just typehint emoji with discord.Emoji
Lemmie Try
And you would have no need to convert them in code
async def lol(ctx, *emojis: discord.Emoji)```
That doesn't accepts more than one emoji
This does
Command raised an exception: TypeError: '<' not supported between instances of 'PartialEmoji' and 'PartialEmoji'
*args gives a tuple in discord
Lemmie see
Ofc how are you gonna sort the emojis list
*, args will give a string
By what are you gonna sort them
*args will give a tuple

That's a different thing
Damn I didn't see
why even sort in first place
Yes
If you really wanna sort them you need to sort them by something comparable
Emojis themselves are not comparable
Like if you wanna sort by name you would have to do something like this
sorted(emojis, key=lambda x: x.name)```
Command raised an exception: AttributeError: type object 'PartialEmoji' has no attribute 'from_str'```
But why this?
You probably have dpy 1.7 and it was added in 2.0
Ahh no way for 1.7?
Why didn't you just typehint like I said
!d discord.ext.commands.PartialEmojiConverter.convert use this
await convert(ctx, argument)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will properly propagate to the error handlers.
Why not just typehint, essentially the same thing
though typehinting is the better way
exactly
how can i make an embed field start in another row?
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
Is there a way to input user discord roles to google sheets?
If google sheets has a public API then yes
yeah ig u can use Google sheets api
Yeah they do have it https://developers.google.com/sheets/api/reference/rest
And yeah I recommend using aiohttp instead of their wrappers because as I can see they are sync
Ye
@spi.command()
async def ping(ctx,x:str,y:int):
if y>100:
await ctx.send("> :x: **The maximum limit is 100**")
else:
for i in range(y):
await ctx.send(x)
I want to break the loop by using a command
can someone answer this one?
@spi.command()
async def ping(ctx,x:str,y:int):
if y>100: return await ctx.send("> ❌ **The maximum limit is 100**")
for i in range(y): await ctx.send(x)
u can disable the command ig not really sure
async def kick(ctx,
member: Option(choice=discord.member,description="Tag the member"),
reason: Option(str,description="Reason",default="None")):
I am using this, yet in member, any input can be given. How to fix that ?
for a discord bot, how would I implement this
subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.stream.reports():
await channel.send(item)
this was in the example page. It says that it yields reports once they become available. So where can I put this in if I want the bot to alert on each report?
Use a task? Idrk
Yeah...but the docs say it yields once the report is available
So.. I guess that works
is there no way to just have this like it is
subreddit = await reddit.subreddit("subreddit")
async for item in subreddit.mod.stream.reports():
print(item)
like not in a loop or a command or anything
Sorry, ain't got an idea
My lint says no do guess not. I'm just not sure what the time in between loop should be
Unless I do bot.run_until_complete
can my bot find if a user has nitro badge in his profile ?
!d discord.User.public_flags
property public_flags```
The publicly available flags the user has.
why do I not see the nitro one here
Cz there's no way
what's the difference between seeing the hypesquad badges and a nitro badge
@maiden fable would this work?
If you have an idea
Do u mean bot.loop.run_until_complete?
Ah yes my bad
Why u calling that tho?
Tbh I'm not entirely sure what it does lol
Is there a way to call it continuously (continuous loop)
what am I supposed to do here
ask them the same question
where
both of them have different designs, prices, and conditions
the badge
not how you get it
when you have both of them
the way you get them
but I'm not asking shit in a server of Danny
those are all toxic
you buy nitro, you submit a form for hypesquad
makes the same sense, you are contradicting yourself now-
I'm not you, and you're not mine me

Hunter's going to ot tag us
!ot
Bump
async def kick(ctx,
member: Option(discord.Member,description="Tag the member"),
reason: Option(str,description="Reason",default="None")):
guild = ctx.guild
embed = Embed(title="Processing...",color=Colour.blue())
og_interaction = await ctx.response.send_message(embed=embed,ephemeral=True)
if member.top_role > ctx.author.top_role:
embed=Embed(title="You can only kick users with a lower role!",color=Colour.red())
await og_interaction.edit_original_messsage(embed=embed)
edit_original_message is wrong ?
i make on reaction add create ticket but i dont know how can i create if channel already have name discord.py
any who can help
i have a class that contains self.sleep = False, however when i try to call the variable, it brings up this error
AttributeError: 'NewGameState' object has no attribute 'sleep'
i have no clue as to why tho
every other variable in the class seems to work, except not this one
i tried changing it to True, still didnt work
did u create instance of the class?
yeah
Boolean values are not callable
Where have you defined self.sleep in the class
In __init__?
yeah, like so
class NewGameState:
def __init__(self):
self.sleep = False
trying to call it in an if statement
if state.sleep:
await asyncio.sleep(3)
Do you have del state.sleep in your code
the state part is due to how the code is written; still works elsewhere tho
not as far as im aware
What is state defined as
state = NewGameState?
It should be defined as state = NewGameState()
Calling a class creates an instance of it, state = NewGameState just assigns it another name
>>> class NewGameState:
... def __init__(self):
... self.sleep = False
...
>>> NewGameState.sleep
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'NewGameState' has no attribute 'sleep'
>>> NewGameState().sleep
False
see the diff?
This does not work because NewGameState is a class object, not an instance object of a class
yeah my code got a bunch of renaming going on
Read this
The only difference is that you added a line that raises an exception because it is what is supposed to happen
Class objects don't have the attributes of their instances
yeah its set up like so
ctx.bot.game_states[str(game_channel.id)] = NewGameState()
state = ctx.bot.game_states[str(game_channel.id)]
See this
>>> class GameState:
... def __init__(self):
... self.should_sleep = False
...
>>> game_state_instance = GameState()
>>> game_state_instance.should_sleep
False
>>>
Why not just state = NewGameState()? Are they in different files?
yep
Well then what is ctx in both of those files
Also it might be that you forgot to put parentheses somewhere else in your code and it's trying to access that
@bot.event async def on_reaction_add(reaction, user = None): if '**🚀 ┇ SUPPORT**\n\n ► If you have any question\n ► If you need any help\n ► Open ticket with reaction on this message\n\n ╭ Spamming in ticket is disabled\n ┊ Ghost ping in ticket is disabled\n ┊ Multiple tickets are not allowed\n ╰ Opening for no reason is disabled' in reaction.message.embeds[0].description and reaction.emoji == '👾' and not user.bot: role = discord.utils.get(user.guild.roles, name="@everyone") chan = await user.guild.create_text_channel(name=f'ticket - {user}') await chan.set_permissions(role, send_messages=False, read_messages=False, add_reactions=False, embed_links=False, attach_files=False, read_message_history=False, external_emojis=False) await chan.set_permissions(user, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True) embed = discord.Embed(description="**🚀 ┇ SUPPORT**\n\n ► Thanks for open ticket\n ► Now wait for a response from owners") embed.set_footer(text="† Creator Matija#4633 † ") msg = await chan.send(embed=embed)
How can i disable multiple channel create
!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.
How to create whitelist channels?
I did something like this:```py
WHITELISTED_CHANNELS = ["123", "124"]
@bot.check
def check_commands(ctx):
return ctx.author.id in WHITELISTED_CHANNELS```
But it doesn't work
Hi i have a question
i have this 8ball script
and i want to make it so that if you do just !8ball it will return a message with you need to include a question
how do i do that ?
because right now it just returns
message is a required argument that is missing.
in the console
@commands.command(aliases=['8ball'])
async def eightball(self, ctx, *, message:str):
if message == '':
await ctx.send("Please include a question like : 8ball questionhere")
just do message:str = None
if not message:
#instead of
if message == '':``` '
okey ill try that
what is MessageReference.resolved and when should i use it?
i did that but its still not returning my message
from discord.ext.commands import Context, CommandError, MissingRequiredArgument
@commands.command(aliases=['8ball'])
async def eightball(self, ctx: Context, *, message: str) -> None:
await ctx.send(message)
@eightball.error
async def eightball_error(self, ctx: Context, error: CommandError) -> None:
if isinstance(error, MissingRequiredArgument):
await ctx.send("Please include a question like : 8ball questionhere")
||pandabweer|| was writing paragraph
If a message is resolved it's a valid retrieved message if it returns None the message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation.
You can't do this since the author didn't mention that required argument is an exception.
Thank you soo much !
i didnt even know @eightball.error was a thing !
So for that we included the error?
if not message:
It's used to check if a message still exists but in python it's better to ask for forgiveness than permission.
It won't even reach that code if you put it inside the command.
"attempting to resolve"?
what is """""""""""resolve"""""""""""""
Ahh but as my usage that works fine for me making different error for every time is time taking
||
||
that won't work, consume rest won't raise MissingRequiredArgument. You have to specify that you need the argument to be passed for it to be raised
@commands.command(aliases=["8ball"], require_var_positional=True)
async def eightball(...):
...
In this case resolved means it found either the message or see if the message got deleted, if the resolve fails the message hasn't been fetched.
Ofc
If it is not mentioned True It is true by default yet
But that's the decorator and those are optional keyword arguments. We're talking about the coro here.
import discord
import random
from discord.ext import commands
from discord_slash import SlashCommand
bot = commands.Bot(command_prefix="!", description = "tools dev by zcronic")
slash = SlashCommand(bot, sync_commands= True)
@bot.event
async def on_ready():
print("ready")
@slash.slash(name="size_femme", guild_ids=[916447427605725194], description="voir les tailes femme us en eu ")
async def size_femme (ctx):
await ctx.send("https://www.sports-loisirs.fr/img/cms/guides%20pointure/Pointures-femme-Nike.jpeg")
@slash.slash(name="size_homme", guild_ids=[916447427605725194], description="voir les tailes homme us en eu ")
async def size_homme (ctx):
await ctx.send("https://www.sports-loisirs.fr/img/cms/guides%20pointure/Pointures-homme-nike.jpeg")
@slash.slash(name="raffle", guild_ids=[916447427605725194], description="voir les sites qui prélèvent ou non lors de raffle")
async def raffle (ctx):
embed = discord.Embed (title = ("Guides des prélevements pour les raffles"),description = ("-"))
embed.add_field(name = ("__sites qui prélèvent__"),value=("-afew\n" "-consortuim\n""-Cornerstreet\n""-Footpatrol\n" "-GrosBaskets\n" "-Hanon\n" "-kickz\n" "-JD sport\n" "-Seventstore\n" "-size\n" "-Slam Jam\n"))
embed.add_field(name = ("__sites qui ne prélèvent pas__"),value=("-Basket4Ballers\n" "-BSTN\n""-Courir\n""-END\n" "-Fenom\n" "-Footshop\n" "-Goodhood\n" "-Kith\n" "-Noirfonce\n" "-One Block Down\n" "-shinzo\n" "-Sivasdescalzo\n" "-SNS\n" "-4 elementos\n" ))
await ctx.send(embed = embed)```
found the message where?
I've got no clue what requires_var_positional is that just seems like it's made up.
i have this error why ?
Your boy doesn't have permission to send the message maybe
he is admin
Full traceback?
!d discord.ext.commands.Command.require_var_positional
If True and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults to False.
New in version 1.5.
Anywhere, like going trough the message history and it fails to fetch and returns a deleted message or an old object that could have been deleted.
but this isnt an async method
?
so resolved is set as a side effect of other methods?
That could work couldn't find it in the docs.
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
i don't understand ahhhhaaaa
First of all you are using an old library, second did you enable application commands inside the scope?
yes but what library can i use
is it usable?
It's used to check if a Message object is valid.
discord.py 2.0
disnake
but what import
Lol you are using disnake
what i have to importt
especially with such an arrogant creator
Oh smh I tought it had a getch of Message.
I still don't get what does := do
ref.cached_message or ref.resolved or await self.channel.fetch_message(ref.message_id)
assigns and returns a value
What exactly do you want to do? This looks like what reference obj does.
Walrus operator.
i need Message object not reference object
Ok got it
So this is inside the Message object, but how are you going to fetch/ get?
wut