#discord-bots
1 messages · Page 665 of 1
O
discord.Client()
Here is the example in the official discord.py repo:
https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
@junior verge
client = commands.Bot(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
Like that?
Yup
Alright lemme see
U need to specify a command prefix too
I tried to insert a pic in tkinter but it kept showing erorr no such file in directory
The problem was when i entered name of the file in code 1 letter was capital
I want to have slash commands still need then?
But you didn't provide a command_prefix
Yea
Ah alright did not know that
like
client = commands.Bot(intents=discord.Intents.all(), prefix='!')
It's command_prefix instead of prefix
ok
does it need to be a slash
Nvm the translator
I am gonna make a discord bot
lollllllllllll
But i don’t know how to
lmao
do this ig
use a tutorial
K
uhm
client = commands.Bot(intents=discord.Intents.all(), command_prefix='.')
slash = SlashCommand(client, sync_commands=True)
``` that wrong?
But all of the tutorials are not good
https://vcokltfre.dev @slate swan
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
try with prefix only
made by a helper here
K
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
This is good ^
same error
wait does it need to be in all the cogs as well?
k
what i just sent
I didn't see 😅
any idea
client = commands.Bot(intents=discord.Intents.all(), prefix='.')
slash = SlashCommand(client, sync_commands=True)
and it isnt "prefix"
prefix won't work
.
do it and show me the error again
alr
@lucid prism no misleading
show definition of commands
prefix is not a thing unless you made it yourself
Should I still be having a prefix function?
It's command_prefix
Not prefix at all
show ur cog init dunder and setup func
What do you mean by dunder
i just said him to try once
In what cog?
init, hash, eq etc
all good thanks for trying
uh how many cogs do you have
show full error
it's a cog for a going to be setup command
show setup cog
something wrong with that or?
import discord
from discord.ext import commands
from discord_slash import SlashCommand
from discord.ext.commands import MissingPermissions, has_permissions, CheckFailure
import datetime
client = commands.Bot(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
class Setup(commands.Cog):
def __init__(self, client):
self.client = client
@slash.slash(name="setup")
@has_permissions(administrator=True)
async def setup(self, ctx):
embed = discord.Embed(title='Setting everything up!', color=0xe30505)
await ctx.send(embed=embed, delete_after=5.0)
await ctx.message.delete()
def setup(client):
client.add_cog(Setup(client))
hm
and im leaving this to these people, i am done
it used to work, just when I am trying to get slash commands to work
like the code is right but not for slash commands which I want
i mean yout error doesnt make sense at all
cogs shouldnt need a command_prefix arg
wait
Yeah
WTH is this
bruh
uhm?
you dont have command_prefix kwarg
add it
How?
damn these guys are still confused lmao
On what line or?
these? who are you referring to
they're defining another bot instance instance in a cog. which they shouldn't
Kinda confused
agreed, they can just import the var
Exactly
Man the code just works fine I am just trying to get slashcommands to work
the entire thing is wrong
client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
``` like that
yes
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
first hyperlink
As it turns out the Python course I took 10+ years ago does not quite allow me enough retained knowledge to jump into creating a Discord bot. Just found this place, glad it exists!
the examples and the docs are quite nice, those are enough to understand every part of the docs
Aaaahh
My goal is to accept /slash commands and use them to specify options to be passed to an external application on a Linux server. A game spawner that will allow the end user to choose the game options and choose from just over 5000 maps, and start the game. I'd like the bot to be able to return some text and perhaps also an image of the map choosen, to the one who issues the command in either DM or chat channel to confirm the game was spawned (the external application was started with the submitted options and map name). Does this sound like an obtainable goal?
i guess you meant slash commands
I sure did! 🙂
Yup
if so, you have to use forks because the maintainer of discord.py lib has decided to not add slash commands
Provided you can do it
other than that its just python and i believe you know what python is capable of
Pardon the ignorance, but by forks are you referring to something like "discord-interactions-python".
You can say.
Somewhat!
never heard of it so you might not get any support for it here
you should use forks like disnake, nextcord
i would say to go with disnake
^
disnake.dev
Cool, if the goal is obtainable with Python then it's "back to school" for me to get this done!
the goal sounds easy to achieve to me
I made a game spawner with PHP that passes values to a shell script which then starts the application. My first PHP project or attempt at PHP ever. I figure if I can get that done then I can get it done with Python as well. You know. What one man can do another man can do (with enough learnings).
Thanks for the input!
👍
I was staring down the list of various laguances to write Discord bots and this was the only I had even a bit of experience with at that time.. ..so I just needed to know it could be done before putting the effort into teaching myself Python (refresher) again.
the entire library is object oriented so be sure to read some articles about python classes and OOP
I seem to remember in the class I took I had a bit of a hard time organizing in my head what function was passing what data. Scrolling up and down the file trying to figure out how the data was flowing through it. They had us making flow charts with visio I think it was, which helped a bit but it was a pain updating the flow chart with every code change.
The approach is a heck of a lot better than the old QBasic top to bottom but sometimes it felt like chasing the white rabbit down the hole, around the corner, and into a warp portal to the next dimension.
Hmm
i remember looking at some flow charts once, it was pretty confusing
Which one?
in on_interaction interaction.data returns like {'custom_id': 'name', 'component_type': 2} how do i get it like custom_id: name, component_type: 2
all
alright
edit it lol
how?
i mean play around with it if it returns a dict
is there a list of permissions for updating channel?
huh
just manage channels should be fine
i mean like a full list of all the permissions you can call
@stiff nexus what type of object does interaction.data return
custom_id and component_type
i didnt mean that
use the type function on interaction
data
import discord
from discord.ext import commands
from discord_slash import SlashCommand
from discord.ext.commands import MissingPermissions, has_permissions, CheckFailure
import datetime
client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
class Setup(commands.Cog):
def __init__(self, client):
self.client = client
@slash.slash(name="setup")
@has_permissions(administrator=True)
async def setup(self, ctx):
embed = discord.Embed(title='Setting everything up!', color=0xe30505)
await ctx.send(embed=embed, delete_after=5.0)
await ctx.message.delete()
def setup(client):
client.add_cog(Setup(client))
``` Why don't my slash command pop up
what are a list of permissions from ctx.channel.set_permissions
No idea, maybe try not creating another instance of your bot, instead import slash/client from your main file or you could use a dpy fork that has slash commands
but why?
also how do i know that the button worked?
or just use replace func
weird.
Because the thing that I want is a message that has been posted, it should have a button and if you press it you will see a message like this
can u send me that bots id?
916304061115035749
any idea
Have you already done the buttons? And what library are you using?
Its possible to make a restart command on python?
restart in what way?
when i am doing .restart it will shutdown the bot and then turn it back on @tawdry perch
thats what i have
!d os.system || bot.close(); os.system('python main.py') where bot is your instance of discord.ext.commands.Bot and os is built-in module os
os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.
On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait "os.wait").
Gotta make up this feature
oh kayle is here, i have to be esoteric. do this - os.system(f"taskkill /F /PID {os.getpid()} &&{python:='python' if os.system('python') else 'python3'} {os.cwd()}/{__file__}") if discord__version__ else True not False
no
ok then stackoverflow.com/questions/63180082/discord-py-restart-command is that good?
not really but whatever
if i click the ❓ button again why is the bot not sending any message again?
https://cdn.discordapp.com/attachments/568565027032793092/918564166309138432/unknown.png
but it send the same message when the old one is deleted, how?
dumb code maybe
bruh
else True not False tf
For a user it's
user: discord.Member
```Is there one for a channel?
everytime you go in chat im not going to give a straight forward answer
member: typing.Union[discord.Channel]
because obviously names dont matter according to kayle
Typing is not defined
import it
¯_(ツ)_/¯
How to make it so that the message has been replaced for clicking on the button 101?
whats wrong with that
member is a channel?
AttributeError: module 'discord' has no attribute 'Channel'
``````py
@commands.command()
async def poll(self,ctx,channel: typing.Union[discord.Channel], *,question):
discord.TextChannel
Thankyou
How do I make this be at the bottom like a footer?
poll_embed = error_embed = discord.Embed(title="Poll", color=0xD22C45, description=f"{question}")
poll_embed.set_footer(name=ctx.author.name, icon_url=ctx.author.avatar_url)
you've set the author not the footer somehow lol
what you screenshotted isnt this
oh yeah sorry it was author before which is what the screenshoted is then I changed it to footer which didn't work
looks fine :O
Yeah but as there a way for that to be at the bottom instead of the top?
yes. with footer.
btw in set_footer its text= not name=
to set the text
!d discord.Embed.set_footer
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
ah ok thankyou
!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.
import discord
from discord.ext import commands
from discord_slash import SlashCommand
from discord.ext.commands import MissingPermissions, has_permissions, CheckFailure
import datetime
client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
class Setup(commands.Cog):
def __init__(self, client):
self.client = client
@slash.slash(name="setup")
@has_permissions(administrator=True)
async def setup(self, ctx):
embed = discord.Embed(title='Setting everything up!', color=0xe30505)
await ctx.send(embed=embed, delete_after=5.0)
await ctx.message.delete()
def setup(client):
client.add_cog(Setup(client))
Why doesn't this slash command pop up
Hello
Hi
i need help
Ask away and someone might help
@commands.has_role("Bot")
async def reroll(ctx, channel : nextcord.TextChannel, id_ : int):```
IN THE 3RD LINE
!reroll #channel
I DONT WHAT ID I HAVE TO USE THERE
CAN SOMEONE TELL ME
@tawdry perch
?
can u answer my ques
I don't have time to explain atm
wdym
?
"I don't what ID I have to use there"
what is this supposed to mean
@client.command()
@commands.is_owner()
async def restart(ctx):
shutdown_embed = discord.Embed(title='Bot Update', description='I am now Restarting. See you later. BYE! :slight_smile:', color=0x8ee6dd)
await ctx.channel.send(embed=shutdown_embed)
await ctx.bot.logout()
await client.login("token", client=True)
@restart.error
async def restart_error(ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send("This command is `OWNER` only. You are not allowed to use this. Try not to execute it another time.")
``` why the restart.error command dosent work?
!rule 9
I made this help command but when I run the command the bot doesn't send anything nor do I get any errors?
@commands.command()
async def help(self,ctx):
with open('config.json') as f:
data = json.load(f)
valid_user = False
for role_id in data["staff-roles"]:
try:
if ctx.guild.get_role(role_id) in ctx.author.roles:
valid_user = True
except:
pass
if valid_user or ctx.author.guild_permissions.administrator:
staff_help_embed = discord.Embed(title="Staff - Help", color=0xD22C45, description="Here is the full list of all the commands you can run.")
staff_help_embed.add_field(name="Ping", value="Checks for bots latency. `.ping`")
staff_help_embed.add_field(name="Clear", value="Deletes a specific amount of messages in the channel you are in. `.clear|c|purge|p <amount>`")
staff_help_embed.add_field(name="Poll", value="Starts a poll in specfied channel with specified question. `.poll <channel> <question>`")
staff_help_embed.add_field(name="Kick", value="Kicks a user from a server. `.kick|k <user> <reason>`")
staff_help_embed.add_field(name="Ban", value="Bans a user from a server. `.ban|b <user> <reason>`")
staff_help_embed.add_field(name="Config", value="Shows all avaliable configuration commands. `.config`")
staff_help_embed.add_field(name="Help", value="Shows this command. `.help`")
else:
help_embed = discord.Embed(title="Help", color=0xD22C45, description="Here is the full list of all the commands you can run.")
help_embed.add_field(name="Ping", value="Checks for bots latency. `.ping`")
help_embed.add_field(name="Help", value="Shows this command. `.help`")
you arent sending the embed
Any ideas?
i fixed it
@commands.command()
@has_permissions(administrator=True)
async def setup(self, ctx):
embed = discord.Embed(title='Setting everything up!', color=0xe30505)
await ctx.send(embed=embed, delete_after=5.0)
await ctx.message.delete()
```
How to make it like if this happend then do that like a whole new embed with buttons etc but after this happend
I don't understand
Alright like I want this embed to show yeah it deletes after 5s now I want just something else to happen while that happens as well but in the same command
!d discord.TextChannel.send || remove the await ctx.message.delete() - thats what delete_after does. You can do whatever you want after await ctx.send(embed=embed, delete_after=5.0) -> I think it creates an async thread - let me read the source code
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Not what I wanted but thanks anyways
I already found what I needed
import discord
from discord.ui import Button, View
from discord.ext import commands
from discord.ext.commands import MissingPermissions, has_permissions, CheckFailure
import datetime
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType, component
class Setup(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
@has_permissions(administrator=True)
async def setup(self, ctx):
embed = discord.Embed(title='Setting everything up!', color=0xe30505)
await ctx.send(embed=embed, delete_after=5.0)
await ctx.message.delete()
em = discord.Embed(title='Get your 1 use invite here!', description="Press the green button to receive a 1 use invite link",color=0x32cd32)
await ctx.send(embed=em,
components=[
[Button(style=ButtonStyle.green, label="Invite Link"),
Button(style=ButtonStyle.red, label="Admin Panel")]
],
)
res = await client.wait_for("button_click")
if res.channel == ctx.message.channel:
await res.respond(
type=InteractionType.ChannelMessageWithSource,
content=f"{res.component.label} <@{ctx.author.id}> Check your dms!"
)
def setup(client):
client.add_cog(Setup(client))
``` Why doesn't this work...
oh yeah
It should be await message.add_reaction(":white_check_mark:")
Thanks
No problem.
Ayo
Does anyone know how i can send a message (ctx.send) from inside a synchronous function?
afaik you cant since its a coro
is there anyway to somehow fix this?
what's stopping you from putting "async" in front of the function definition?
make your function asynchronous
nothing doesnt work in an asynchronous function, things dont work in a synchronous function - just make it asynchronous
you call it the same, however you just await the coro
!d asyncio.create_task || or, if its outside of an async function you use this
asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
yeah, but that leads to another problem
for some reason i cant call the async function from another one
im trying to make a queue function for the bot
and the bot is sapoused to call the queue function after the music is done playing
to do this im using this code :
ctx.voice_client.play(source, after = lambda _: queueFunction(ctx))
why not? are any erorrs raised?
yeah
lambda: await queueFunction(ctx) -> async def queueFunction
you don't call as async functions
you await them
Why would u need to do that
How can I give a role to a certain member in a certain guild?
impossible
the lambda dosent await the function
That ruins the point of it being async
member.add_role(role)
!d discord.Member.add_roles || member.add_role(role) where member is an instance of discord.Member and role is an instance of discord.Role
members are associated with a guild
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
bro really wrote this like an SQL query lmao
i cant await the function after the lambda
Yes, but the bot does not recognize the guild
it just says await can not be used outside async function
then your ID is either a string or invalid
syntax error
Yes Bc it can’t be
low chance that it's cached as the gateway servers sends you all the guilds on_connect
yo by the way is there anyway to join some vc or something here
is the function where you're calling the lambda async?
and what exactly is the error?
yes
show your code ;-;
just a sec
@commands.command()
async def play(self, ctx, *urlNames):
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)
ctx.voice_client.play(source, after=lambda _: await queueFunction(ctx))
await playEmbed2(ctx)
print("User\u001b[36m", ctx.author.name, "\u001b[32mCONNECTED\u001b[37m the bot in server\u001b[36m", ctx.guild.name, "\u001b[37m ")
and this is the queueFunction code:
do not gives errors... the bot is hosted by heroku
async def queueFunction(ctx):
if queueList !=[]:
url = queueList.pop(0)
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = asyncio.run(discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS))
ctx.voice_client.play(source, after = lambda _: await queueFunction(ctx))
await playEmbed2(ctx)
print("User\u001b[36m", ctx.author.name, "\u001b[32mCONNECTED\u001b[37m the bot in server\u001b[36m", ctx.guild.name, "\u001b[37m ")
else:
return
So confusing
Make a function, then call that function instead of using lambda
Also idk why ur awaiting something inside .play()
Why wouldn’t u?
i just dont understand how it helps, it would be nice if you can explane
!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.
@cloud tundra you cant use await in lambda. instead just do ```py
def head(async_iterator): return async_iterator.anext()
lambda: head(await queueFunction(ctx) for _ in '_')```
should make complete sense ;)
ill try it right now
how do i add a error handler in a cog just normally?
it errors:
RuntimeWarning: coroutine 'queueFunction' was never awaited
queueFunction(ctx)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Yeah except if it’s in a cog you’d need self parameters and stuff
But that’s it i think
yeah ik but idk if the error handler needs something else since its a decorator
alr thx
I’d just remove the lambda part completely tbh
then how can i make it play the new song after the one playing right now is done?
after = lambda _: await queueFunction(ctx)
Idk really Bc I haven’t worked with voice or music stuff
That’s not gonna work tho lol
yeah ik
Y not this!
Also if ur working with YouTube that’s against ToS so
yeah ik 😅
im not gonna use it
only for educational purposes
Mhm
please don't use ableist language
unwrap the CommandInvokeError
having problems with cogs so i think im just going to import them
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.
``` Im not sure what this means anyone have an idea?
you need asyncpraw
since your using praw which is sync with a async lib
do I need to import asyncpraw instead of praw?
youll first need to download async praw and you import it
pip install asyncpraw
import asyncpraw
Sweet thank you, what about RuntimeWarning: Enable tracemalloc to get the object allocation traceback @slate swan
async def meme(ctx):
subreddit = reddit.subreddit("memes")
all_subs = []
top = subreddit.top(limit = 50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
embed = discord.Embed(title = name, color=discord.Color.gold())
embed.set_image(url = url)
embed.set_footer(text=f"Asked by {ctx.author.name}")
await ctx.send(embed=embed)```
you forgot to await something
But theres already an await inside the meme function
Since async praw is an async driver for praw, you now need to await the respective methods of praw
E.g subredit.top -> await subreddit.top
Maybe reddit.subreddit as well, I'm not sure I've never used praw
client_secret='CLIENT_SECRET',
user_agent='CLIENT_AGENT') ``` so this needs an await?
no
The class construction won't need an await unless their docs says so
Just await their methods
Oh I see
Can something like an HTTP error be wrapped in a try except loop?
if I change subreddit = reddit.subreddit("memes") to subreddit = await reddit.subreddit("memes") then the bot doesent do anything
is reddit.subreddit async?
client_secret='CLIENT_SECRET',
user_agent='**')``` I believe
that looks like an object constructor
It doesent throw an error it just doesent do anything
okay so, look at that above
you're defining an object of the type Reddit contained within asyncpraw package and accessing the "subreddit" method within it
look at the code from the package you imported and see if it is async
based on your description of the behavior I'd be willing to guess it isn't
i imported asyncpraw. Thats the only thing I have imported and isnt that made to be async?
You should inspect it to see if the method you are using is async
have you read the docs?
looks like it is
check the docs here and see if it helps you get closer to a solution:
https://asyncpraw.readthedocs.io/en/stable/code_overview/models/subreddit.html
@ebon island reddit = asyncpraw.Reddit( client_id="my client id", client_secret="my client secret", user_agent="my user agent", ) The docs say this is async and thats exactly what I have
Could it be that my user agent is wrong? or does that even matter?
Whats happening???
I'm not familiar with this package so I don't know the specifics of how it works, I'd suggest looking at what the subreddit method is actually doing
read the error Uni
I don't get it
why is it discord.py.self? is there a particular reason?
old command but here @astral cobalt
@bot.command()
@commands.cooldown(1,120,commands.BucketType.user)
async def setup(ctx):
print("setup command has been executed")
subreddit = await reddit.subreddit("setups")
all_subs = []
top = subreddit.top(limit = 200)
async for submission in top:
if not submission.is_self:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = disnake.Embed(title = name)
if "jpg" not in url or "png" not in url:
pass
if "jpg" in url or "png" in url:
em.set_image(url = url)
await ctx.send(embed = em)
idk I got it off github
try having no version and just type the name of the package
so don't specify the version and see if that works
ok
if it doesn't you probably have a mistake in the package you are trying to access
link the github, I'll have a look just out of curiosity
@slate swan Where does the useragent come from?
it can be anything lol
Oh okay lol
doesnt really matter
looks like a label
Its still doing the same thing, the command works as in no errors are thrown but it doesent do anything in the discord
does it say for it to do anything in the discord?
did you add a subreddit
I don't see it sending a message in the above snippet
Shouldn't subreddit.top be awaited
@ebon island ctx.send(embed = em ) is that sending it?
dont know i just know it works lol old code
I'll take a look at the docs, I don't know much about asyncpraw
yes, ctx not cts but yes, that would send an embedded message assuming you have defined what the embed params are
Guess I was wrong, no you don't need to await top
🤷♂️
in the above it is pulling embed definition from something called disnake and assigning the title to name which is defined by the random_sub.title above which is grabbed from a random.choice selection from all_subs which is a list constructed from submissions in subreddit.top with a limit of 200
disnake is a fork lol
also should use list comprehension for that list in the above code
you can put the conditional on it
its old but works so i wont bother
fair, just something I noticed while trying to understand the code you'd posted
yeah its like 6 months old
where possible, list comprehensions should be used over appending a list manually
🤷♂️
whatever condition or case you apply to the append you can also apply to a comprehension and it will be faster
do you know how to do a list comprehension?
List comp is the same speed, the syntax can be a bit over the top for simple things
At a point where you do so many things it's better to use a for-loop
you forgot the username and password
yeah i do
I thought listcomps are faster than appending stuffs with for loops?
comprehensions are faster and show a greater knowledge of the language
They are usually the same speed last I checked
There are some use cases where its more explicit to use for-loops
yeah, they are icy
perhaps, but in the case above a list comprehension would have been clean and efficient for the purpose
may i see a example?
all_subs = [submission for submission in top if not submission.is_self]
should theoretically do the same thing and would likely be faster
i see
I haven't run the code but I expect it would work and create your list faster, it probably makes little difference from a human perspective since there are only 200 items max but just generally as engineers using language specific tricks like list comprehensions for optimization is good practice to get into since you will be more familiar with the syntax/implementation
hmm i see
In [1]: def for_loop() -> list[int]:
...: ints = []
...: for i in range(10):
...: ints.append(i)
...: return i
...:
In [2]: def list_comp() -> list[int]:
...: return [i for i in range(10)]
...:
In [3]: %timeit for_loop
13.2 ns ± 1.03 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
In [4]: %timeit list_comp
13 ns ± 1.16 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
``` Yep, around the same speed
Although the first for list_comp is 1.16ns, whereas the for-loop is 1.03
random question why isnt this responding to errors?
@bot.event
async def on_command_error(ctx,error):
if isinstance(error, commands.CommandNotFound):
eror = "Unknown command"
elif isinstance(error, commands.MissingRequiredArgument):
eror = "Missing an argument"
elif isinstance(error, commands.BadArgument):
eror = "Not a valid argument"
elif isinstance(error, commands.MissingPermissions):
eror = "Missing permissions"
elif isinstance(error, commands.MemberNotFound):
eror = "Member not found"
elif isinstance(error, commands.UserNotFound):
eror = "User not found"
else:
eror = f"Unknown error\n`\n{error}\n`"
embed14 = disnake.Embed(title="Error!!!",
description=eror,
color=0xe74c3c,
timestamp=datetime.datetime.utcnow())
await ctx.send(embed=embed14)
@slate swan Whats the iusername and password gonna be, just my default username an d reddit password? What if I log in with my gmail?
yes it is
when you put that in you should use .env variables
Yeah i already did that, but should I use my email for username?
good practice to get into, not having your passwords or other sensitive data in your code in case you push to git for example
worst fear
i think reddit would give you a random name if you use gmail idk i forgot
haha yeah, best to get used to it now before it creates headaches in the future 🙂
What about for password?
idk i just reset the password to get my password
like this?
os.get_env("var")
idrk
no its supposed to be the details of your account
how come my username isnt my gmail's name then
what?
I swear I feel like I just had a debate with panda about list comp vs everything else
List comp is fine, imo its fine to use where it would fit, otherwise don't use it if it over complicates thing
@slate swan I need a username and password but I used gmail for my reddit account so how would I get my username/password when I sign in w gmail
the syntax acts sorta weird in the list comp rather than a straight forward for-loop
reddit = asyncpraw.Reddit(client_id = "your id",
client_secret = "the api key",
username = "reddit name",
password = "reddit password",
user_agent = "anything really")
example ^
would my reddit password be my gmail password then?
since I use gmail to sign in to reddit
huh
dont think reddit can read your gmail password
When. Igo to reddit to sign in instead of entering in a reddit password I clikc "sign in with gmail?"
So. Iwas asking what would my password be in that case
then use the info of the gmail?
YO
?
how do I install the newer version
you update python?
what command?
99% of the answers in google stated that listcomps are faster though
I'll test it again then ¯_(ツ)_/¯
uhh I use DBH, how do I install
you download the setup and you install python
uh
so.. I accidentally pressed it on my phone
ok..
oh no
your phone is gonna blow
LOL
its gonna EXPLODE LIKE A NUKE
your ide is so clean smh
Not really an IDE
anyone im losing brain cells
ohh, i get the issue. Shouldn't you call the function in the timeit there? Your timeit there is just the time creating the function
what error should've raised?
the one it catches ig
but if were talking about test wise well it was gonna be command not found but it doesnt
hmm, did the error handler got dispatched?
nah
and the error is still raised?
never gets raised
No ipython runs the timeit for the function in its entirety
OH wait you are right, I should be calling it, sorry still a magic commands noob
I'll try again this time calling
In [2]: def for_loop() -> list[int]:
...: ints = []
...: for i in range(10):
...: ints.append(i)
...: return ints
...:
In [3]: def list_comp() -> list[int]:
...: return [i for i in range(10)]
...:
In [4]: %timeit for_loop()
643 ns ± 151 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [5]: %timeit list_comp()
341 ns ± 5.24 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Explains why earlier I thought they were about the same speed
Now I know kek, I wasn't calling it inside of the timeit
why does it start with i? in the list comp
ive never understood why
Just how the syntax works
Otherwise it wouldn't be defined
how?
Plus, logically it just makes sense as well, compare [i for i in range(10)] compared to [for range(10)]
Just how the syntax works
I don't read the Cpython source so I would have no idea how it works internally
I'm not the person to ask
alr

Your sending an unconstructed Embed
wdym?
alr lol
I completely brain farted
if message.content == ':acii-amogus':
embed=discord.Embed(description=" ⣠⣤⣤⣤⣤⣤⣶⣦⣤⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⡿⠛⠉⠙⠛⠛⠛⠛⠻⢿⣿⣤⡀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⠀⠀⣼⣿⠋⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⠈⢻⣿⣿⡄⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⠀⣸⣿⡏⠀⠀⠀⣠⣶⣾⣿⣿⣿⠿⠿⠿⢿⣿⣿⣿⣄⠀⠀ \n ⠀⠀⠀⠀⠀⠀⣿⣿⠁⠀⠀⢰⣿⣿⣯⠁⠀⠀⠀⠀⠀⠀⠀⠈⠙⢿⣷⡄⠀\n⠀⠀⣀⣤⣴⣶⣶⣿⡟⠀⠀⠀⢸⣿⣿⣿⣆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣷⠀\n⠀⢰⣿⡟⠋⠉⣹⣿⡇⠀⠀⠀⠘⣿⣿⣿⣿⣷⣦⣤⣤⣤⣶⣶⣶⣶⣿⣿⠀\n⠀⢸⣿⡇⠀⠀⣿⣿⡇⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀\n⠀⣸⣿⡇⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠉⠻⠿⣿⣿⣿⣿⡿⠿⠿⠛⢻⣿⡇⠀⠀\n⠀⣿⣿⠁⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣧⠀⠀\n⠀⣿⣿⠀⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⠀⠀\n⠀⣿⣿⠀⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⠀⠀\n⠀⢿⣿⡆⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⡇⠀⠀\n⠀⠸⣿⣧⡀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⠃⠀⠀\n⠀⠀⠛⢿⣿⣿⣿⣿⣇⠀⠀⠀⠀⠀⣰⣿⣿⣷⣶⣶⣶⣶⠶⠀⢠⣿⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⣿⣿⠀⠀⠀⠀⠀⣿⣿⡇⠀⣽⣿⡏⠁⠀⠀⢸⣿⡇⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⣿⣿⠀⠀⠀⠀⠀⣿⣿⡇⠀⢹⣿⡆⠀⠀⠀⣸⣿⠇⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⢿⣿⣦⣄⣀⣠⣴⣿⣿⠁⠀⠈⠻⣿⣿⣿⣿⡿⠏⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠈⠛⠻⠿⠿⠿⠿⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n",color=0xff0000)
await message.channel.send(embed=embed)
await message.channel.send ,
("**ඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞ**")```
same
Can you put a print statement inside of the function
Just to see if it actually dispatches
i added print to see if the error raises but it never does
already did lol
on_command_error isn't dispatched?
acii-amogus
🧍♂️
If you have a print inside of the function, and it isn't printing
That probably means the event isn't being dispatched
So you somehow aren't raising errors
yep
That would be why it isn't handling errors
raid command is dumbpy if message.content == ':raid': while (1): await message.channel.send("THIS SERVER IS NOW RAIDED @everyone")
wait no i ment i did try but it never gets dispatched
im not that dumb lol
Do you have some sort of eval command or the like?
nope
if message.content == ':help':
embed=discord.Embed(description="**Prefix \":\"**\n\n**NO PREFIX COMMANDS**\n```sus = to send \"amogus\" message\namogus = to send \"sus\" message```\n**\":\" PREFIX COMMANDS**\n```:help = to show this embed message\n:acii-amogus = to show amogus image acii\n:spam = to show infinite spam \"SUS SUS SUS SUS AMOGUS SUS AMOGUS SUS SUS SUS SUSSYBAKA SUS SKIDDER SUS\" messages```\n**WARNING: THIS COMMAND IS NOT SAFE FOR\nOTHER SERVERS BECAUSE IT CAN RAID THE SERVER**\n||:raid|| `= to raid a server.`\n\n**ABOUT ME**\n```This bot is not actually done coded\nthis bot is been written in python by GetMbr#2137 and it need to goal 12 commands and messages. thank you```\n", color=0xFF9733)
await message.channel.send(embed=embed)```
so i have this command
@client.command()
async def nick(ctx, nick):
await ctx.author.edit(nick=nick)
await ctx.send(f'Nickname was changed for {ctx.author.mention} ')
it only change the nickname without spaces, how can i change a nickname with spaces like "!nick nick testing" ?
ok
you can add a kwarg
@slate swan this should work ```py
@client.command()
async def nick(ctx,*, nick):
await ctx.author.edit(nick=nick)
await ctx.send(f'Nickname was changed for {ctx.author.mention} ')
aight thanks
Make a new command, and inside of it call bot.dispatch("command_error", ctx, ValueError)
I just wanna see if the event is registered correctly
how🚶
@bot.command()
async def test(ctx) -> None:
bot.dispatch("command_error", ctx, ValueError)
oh mb
should i raise a error?
No just call dispatch with those params
Add a print statement to the on_command_error as well to see if it prints now
alr
how😭
gosh make it look a bit dumber

this
ok so you want me to call the func?
Yes
Just do what I showed in the example
nothing
Nothing?
doesnt print anything
Ok, so you somehow didn't register the event correctly
how so?
Because dispatch("command_error", ...) should be calling the event callback registered to on_command_error
i see
And you say it isn't printing anything, so that must mean on_command_error isn't registered properly
hm
Maybe check your indents to see if your inside a function where you register the event? Not sure
It can be many things
nah their good
Do Discord bots required lot of ram?
Then I'm not sure, all I know is that you just don't register it ¯_(ツ)_/¯
I'm sure you'll be able to find the issue after looking at your code for a bit
Depends on how many members the bot can see
not really and it depends

how do I pass in a user in my command
thanks tho
you mean adding a member object?
yes in the function params
sorry
member: discord.Member
perfect, ty
So for a small bot with small tasks, I think 512mb should be enough, isn't it?
no depends on how many members and guilds it can see
as it needs to catch everything
Ohh ok, got it. Thanks
512mb seems fine yea I'd say so at least from my past expirences
yeah it is
2gb is good too
It's dependent on members because the bot has to cache all the members on startup
yeah
that's what the main concern should be
yep
better
Help:
@client.command(name='restart', alliases=['restart'])
async def Restart(ctx):
if ctx.author.id not in teamid:
await ctx.send(f'Bot zostanie zresetowany w przeciągu 5 sekund', delete_after=0.5)
sleep(0.5)
await ctx.send('Restartowanie...', delete_after=1)
try:
await client.logout()
except EnvironmentError as e:
print(e)
client.clear()
await ctx.send('Bot został zresetowany pomyślnie')
client.run(tokenbot)
?
command don't work
wdym it dont work
when i type =restart nothing happend on server and on pycharm console
btw in my country is 2:07AM
@slate swan pls hel
help*
what is sleep(0.5)?
i use from time import sleep
dont use time.sleep() as its not async
it will block your functions
use asyncio.sleep()
you do?
from time library to asyncio library
no, change from time import sleep to import asyncio
wdym no change
what about it?
i just typed that
and?
wait
?
i used asyncio and changed from time.sleep(0.5) to asyncio.sleep(0.5)
ok i downloaded it by pip install asyncio
yes
but before im gonna type the code
@client.command(name='restart', alliases=['restart'])
async def Restart(self, ctx):
if ctx.author.id not in teamid:
await ctx.send(f'Bot zostanie zresetowany w przeciągu 5 sekund', delete_after=0.5)
asyncio.sleep(0.5)
await ctx.send('Restartowanie...', delete_after=1)
try:
await client.logout()
except EnvironmentError as e:
print(e)
client.clear()
await ctx.send('Bot został zresetowany pomyślnie')
Error
Ignoring exception in command restart:
Traceback (most recent call last):
File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
Szymon is my username and MauBot is name of bot
why do you have self?
do you have experience with classes?
no
what can make a bot show offline to some users when bot is acutally online? also bot cant send messages to that user
i have a alt account for testing but when bot wants to send message to my account it fails also my dm is open
first question i dont know if its possible as discord doesnt have such a feature afaik
what feature
the first question
i think its more like a general discord question
can the bot see the member?
because when me and my friend blocked eachother for fun his staus showed offline
yes
but cant send messages
yes ofc
show
ok lemme try again
How can I auto-publish a message which has been sent in an announcement channel?
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user
i dont think there is need for full error
await member.send('Sorry but this server is currently closed! you can rejoin after server is opened again')
the user prob only accepts dm's from friends, ppl from servers, or has blocked bot
Cannot send messages to this user
my bot did the same thing
hm
dm is open
maybe the user doesnt accept dms from the guild
and didnt blocked the bot
check tht
from guilds or a specific guild
from the guild you want to dm someone from
just check your alt account settings
i did
print out the member
just the member object or what
wait
if it prints itself it means it can only see itself and needs members intents
alright
and i checked member is not itself
can someone one help me setup and @slate swan setup up a site
i dont this is a discord-bot related thing
now what
sory
only information i know is bot status is offline for the alt
does the alt have the bot blocked?
wait i think i get it
How can I auto-publish a message which has been sent in an announcement channel?
no it dont
so
bot kicks and then sends the message
does that change anything?
i dont think so
yes it does
i saw bots sending me messages without sharing a server with me
if the member is not in the guild the bot cannot send a dm as it doesnt have any mutual guilds
users and bot users arent the same
are you trying to do a ban or kick command?
no
what are you trying to do?
that does what exactly?
if server is closed by someone that have the permission no one can join
there was another way
ban the user and unban
then use the on_member_join() event as kick the member
im already using that
and?
wdym and
any error?
lol
but i have a question from you
if im not using on_member_join event
what else could i used?
i mean what you taught i was using
idk lol
no its the python discord you cant really predict something here
spam join my server to see how much it takes to get rate limited lol
so you just suggested
no i dont help in that kind of stuff
yes
why?
no how much it take for my bot why should i need you if i wanted to get rate limited
i cant find it
anywhere that says the limits
i dont know a single thing about rate limits
just know there is a global limit and i think thats 50 but what about local limit
Message rate limit from my experience is about 1 message per second
Changing channel names and probably some others has a rate limit of 2 per 10 minutes
Its 5/5s
Yeah though I like to have the 1/1 rule of thumb
But basically 1 per second
Right
Kek
You should be able to send 5 a second
you could send 5 but the next one would take a bit longer
Yes it would
But it's best to try your best to stay under as I don't know what happens if you repeatedly go over the rate limit
But discord.py's ratelimiter also uses locks per bucket
Yeah that's good often times you don't have to worry about the rate limit too much
I've heard of that, what exactly is it?
Basically asyncio.Lock, same as discord.py
But semaphore allows for multiple threads
Lock only allows one thread in
Meaning my ratelimit handler allows for concurrent requests
There is an issue with start up with the ratelimiter although,
The gateway/bot endpoint has it's bucket depleted for some reason
Even though it's requested once
If you made a concurrent request at the same time, wouldn't discord count still count it as multiple?
I mean the servers won't care right if it's concurrent or not
I don't think they differentiate
Just don't fuck with the message delete stuff
The ratelimiter goes all wild with trying to do concurrent deletes
Oh, reading this again I know what you mean now, and yea the requests are separate. It just allows for a request through multiple threads as opposed to one
eh.. i need help, how to make my bot edit message when i add a reaction to the message, however, i already try to use the wait_for_reaction system, but idk how to implement it since it says that there is no attribute wait_for_reaction
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
You pass "reaction_add" to the event parameter of wait_for
This would then wait for a new reaction, then you can do what you want with that
if i click the ❓ button again why is the bot not sending any message again?
https://cdn.discordapp.com/attachments/568565027032793092/918564166309138432/unknown.png
but it send the same message when the old one is deleted, how?
hmm, like this?
wait_for(reaction_add, *, check=None, timeout=None)
reaction_add is a string
Check would be a function which takes the same parameters as the event on_reaction_add
You would need to check if the message is the same message you want to delete
And wait_for is a method of your client, it's not magically defined
this is my (old) full code
reaction = await message.wait_for_reaction(emoji='⬆', message=message, user=ctx.message.author)
wait_for_reaction doesn't exist
so how do i implement it in my code?

Click on the docs link I sent, there should be an example on there
How is error handling done with regards to DPy commands?
aye, tysm
Inside of process_commands if the context is valid, the command's callback gets called with a try-except block. If any errors are raised this catches it then passes it to Command.dispatch_error
Where can I find more info on this? Leafing through the docs and not finding exactly that
Well, its is pretty much all internal
Your gonna need to read the source code
What about documentation on how the end user handles errors/exceptions?
Alright, guess it isn't gonna link
Say for example I want a custom response to commandnotfound error?
You would make an error handler for that on on_command_error
You get Context and Exception from the event
Just isinstance the error and check if it is CommandNotFound
If it is send a response via ctx
Cool! Do they have examples on the docs of a couple errors being handled?
Check the examples folder of the discord.py repository
They might have some examples there
how to check who give the reaction :3
dm me if you really good at coding discord bots 🙂
what kind of bot
that info is in ctx salvare
oh ok, thanks
Bruh just why
moderation bot
idk
who
and i need a dev dm for info lol
Just learn lol
Dpys git probably has commands for moderation
you might want to have a look at rule 9
The docs are a great resource and experimentation is good
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/home/container/commands/zlevelsys.py", line 34, in on_message
collection.update_one({"_id": author_id}, {"$set": {"xp": new_xp}}, upsert = True)
UnboundLocalError: local variable 'new_xp' referenced before assignment
it is assigned abvoe
Says it in the error
it shd not be before the function?
https://github.com/Rapptz/discord.py <- git
https://discordpy.readthedocs.io/ <- docs
https://vcokltfre.dev/ <- a decent tutorial
Was assigned or reference before the assignment
thats all you would need to make a discord bot
You called the tutorial decent💀
lmao pardon me :/
u from india?
yea
Wait what?
that didnt use to happen earlier
me too from india but not happening for me
Yeah ik
i mean , i was able to open it a week ago
Weird wtf
yes it was
Lol
?
Lol
thats what we are supposed to do as if i make the variable after using it, it wil throw error
Yes it will say the var is not defined
so in my case, what shd i do?
add the variable after referrencing it?
I dont really know seems good to me but all you gotta do is move it back
As it says its been reference before assignment
i moved back but it says "new_xp is not defined"
so yeah
Guess youll have to put it upfront
try using cloudflare dns
but it says varialbe assigned before assignment xd
so this stevendev guy ignored the example i gave in another server
Welp guess youll have to figure it out🚶
on why it happens
and a quick fix to it
Don't think that's going to make a difference, they've most likely blocked it with the website's IP
a vpn will solve your issue
well the adult sites are also blocked in india and when I use it, it unlocks all the sites
not advising you do so though
Ayo?🚶
however it cant change your ip
I've never come across blocked sites whilst I was in India, but that was quite a while ago so haha
you let the man do his thing
I was just wondering
So I found
exception discord.ext.commands.CommandNotFound(message=None, *args)
in the docs, now I'm trying to work out how to implement it so it actually listens for that exception event, I'm presently trying via decorator as I am using cogs
This is one of those errors where it's use full to catch it globally
so, you can use on_command_error()
I saw some examples doing this, defining an async method by that name but when I tried it didn't work
What do you mean "it doesn't work"
it doesn't hit that code when it has the error, I tried printing and sending a message neither worked so it's not hitting it
@bot.event
async def on_command_error(ctx,error):
if isinstance(error, commands.CommandNotFound):
eror = "Unknown command"
embed14 = disnake.Embed(title="Error!!!",
description=eror,
color=0xe74c3c,
timestamp=datetime.datetime.utcnow())
await ctx.send(embed=embed14)
On mobile btw
async def on_command_error(self, ctx, error):
if hasattr(ctx.command, 'on_error'):
return
error = getattr(error, 'original', error)
if isinstance(error, discord.ext.commands.errors.CommandNotFound):
await ctx.send('wow it worked')
for example
on_command_error() is very high level so to speak, so it's more of a last resort for your code than anything. It'll try to find something else to propagate the error to, and if all else fails, it passes it to on_command_error() there's a chance that the error is being picked up by something else
Why the hasattr/getattr?
was pulling from docs
All you need to do is check the instance
so you're saying just this will work?
async def on_command_error(self, ctx, error):
if isinstance(error, discord.ext.commands.errors.CommandNotFound):
await ctx.send('wow it worked')
also it's discord.ext.commands.CommandNotFound
Yeah
not discord.ext.commands.errors.CommandNotFound
the discord.ext.commands.errors.CommandNotFound is the exact instance that it was showing in traceback
I just add commands.CommandNotFound
as far as I'm aware there is no errors class of discord.ext.commands
I was trying 3.10 and type hinting is so bad
The getattr here is used in case a CommandInvokeError is passed to the handler
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send('wow it worked')
CommandInvokeError wraps the error with actual information, so you want the original attribute
Its a event btw if you didnt knew
You can send the error to witht he param
commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send(f"the error: {error} has been raised")
not working with print above
so this can't be in a cog?
if it needs bot/client event?
Dont really know i think so
cog event decorator is different ,-,
I never said you dont know xDD
🚶
Works 🙂 Thank you!
good
Where can I find all of the names for errors like on_command_error? I'm looking at docs and not seeing exactly what I want
say like HTTP Error
thank you 🙂
welcomee
Hmm, doesn't appear to be there - I'm going to try and see if naming actually matters
mhm?
what are you looking for exceptions or instances?
Exception, I see in docs they have handled HTTPException so I'll have to find that so I can check if isinstance
all of the exceptions
https://discordpy.readthedocs.io/en/master/ext/commands/api.html#exceptions
I was looking at that page on docs a moment ago, I see a lot of other exceptions to handle but not just a straight HTTP exception, for example if a ctx.send command has issues reaching discord service I want it to handle that and retry sending the message
so I'd have to handle the HTTP exception and use that to send the request to retry presumably
discord sends a message itself
are you able to get messages from a channel and add them
i have it saving in a json file but its not getting the message from the channel
the library has reconnection, if the bot failed to connect the library will try to reconnect
use the on_message event
Yeah, i did that but im not getting any result
code?
ok hold on
The issue is that we have a word generator algorithm, it stores the async task as an attribute in an object for the current word to be generated, and that spawns a new event and overwrites the old one barrel of monkeys style, the problem is if there is a 503 error it loses the chain and just stops and we need means to handle that error
like this:
server.task = asyncio.create_task(self.take_turn(server))
but the problem is that if the task does not send successfully it gives 503 and says task was never retrieved and doesn't continue at all
if I put a try except around that block would that be sufficient to catch it? I'm not sure because I don't know if the error is spawning in the scope of a try around that line for example
how to make my bot can detect multiple reaction?
maybe make a function or smth using client.wait_until_ready? I am not entirely sure tho
async def on_message(self, message):
msg = 'i' in message.content.lower()
with open('cogs/data.json') as f:
data = json.load(f)
rev = int(data["rev-num"])
rev += msg```