#discord-bots
1 messages · Page 210 of 1
File "main.py", line 1986
await ctx.send(f'The game is now starting! {player_one} vs {player_two}. {current_player}'s turn')
^
SyntaxError: unterminated string literal (detected at line 1986)
i am aware, that is exactly what I have done
Your string is already closed
Use double quotes instead
await ctx.send(f”The game is now starting! {player_one} vs {player_two}. {current_player}”s turn')
This?
Select bot
No
await ctx.send(f"The game is now starting! {player_one} vs {player_two}. {current_player}'s turn")
Show all options
Did you enable bot in the bot tab
try refreshing your page
🤨
@vestal shale don't use a free host, especially not a free discord bot host they're extremely sketchy
I made my own bot but I want to host it so it is online 24/7
just use your pc
or a raspberry pi
I dont keep it on 24/7 but I have a raspberry pi
you can host it there pretty easily
Any recommended yt tuts or something?
you'll pay .15c at most for power every day its nothing
I dont care about the bill
just plug it in, transfer all of your code to there, and then ssh into it and run it
As long as its reliable
you can use SCP to transfer code
get filezila on your pc and raspberry pi
automate the ftp for both sides and trust me as long as the raspberry pi goes undisturbed it will be more reliable then the missus
why filezilla bruh
well any ftp will work xD
scp is already installed
and it uses ssh
you just have to enable it in the raspberry pi settings
but you may want to buy a hdmi to mini hdmi adapter to fix the lag when connecting via vnc when making it headless
File "/home/borderlessgaming/Desktop/Fox News Discord Bot/FoxNews.py", line 43, in check_new_videos
await alert_channel.send(f"New Tucker Carlson video: https://www.youtube.com/watch?v={video_id}")
AttributeError: 'NoneType' object has no attribute 'send'
Task exception was never retrieved
future: <Task finished name='Task-135' coro=<schedule_videos_check() done, defined at /home/borderlessgaming/Desktop/Fox News Discord Bot/FoxNews.py:55> exception=AttributeError("'NoneType' object has no attribute 'send'")>
Traceback (most recent call last):
File "/home/borderlessgaming/Desktop/Fox News Discord Bot/FoxNews.py", line 57, in schedule_videos_check
await check_new_videos()
File "/home/borderlessgaming/Desktop/Fox News Discord Bot/FoxNews.py", line 43, in check_new_videos
await alert_channel.send(f"New Tucker Carlson video: https://www.youtube.com/watch?v={video_id}")
AttributeError: 'NoneType' object has no attribute 'send'
source
import os
import googleapiclient.discovery
import discord
import asyncio
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/home/borderlessgaming/Desktop/nimble.json'
youtube = googleapiclient.discovery.build('youtube', 'v3')
api_key = os.getenv('YOUTUBE_API_KEY')
youtube = googleapiclient.discovery.build('youtube', 'v3', developerKey=api_key)
alert_channel_id = ('1082943979772989491')
search_query = 'Tucker Carlson:'
async def check_new_videos():
search_response = youtube.search().list(
q=search_query,
type='video',
channelId='UCXIJgqnII2ZOINSWNOGFThA',
order='date',
part='id,snippet'
).execute()
video_id = search_response['items'][0]['id']['videoId']
if video_id != os.getenv('LAST_VIDEO_ID'):
alert_channel = client.get_channel(alert_channel_id)
await alert_channel.send(f"New Tucker Carlson video: https://www.youtube.com/watch?v={video_id}")
os.environ['LAST_VIDEO_ID'] = video_id
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
os.environ['LAST_VIDEO_ID'] = ''
client.loop.create_task(tasks_loop())
async def schedule_videos_check():
while not client.is_closed():
await check_new_videos()
await asyncio.sleep(600)
async def tasks_loop():
while True:
await asyncio.sleep(60)
asyncio.create_task(schedule_videos_check())
client.run('')
how come i get this when i call voice_client.stop() i want to stop the current track and start a new one when the user wants it
2023-03-08 18:19:06 INFO discord.player ffmpeg process 7948 has not terminated. Waiting to terminate...
2023-03-08 18:19:06 INFO discord.player ffmpeg process 7948 should have terminated with a return code of 1.
but it just doesn't play when i call voice_client.play() after this
out of the box thinking 
async def play_next_track(voice_client):
# Stop the current track and wait for the FFmpeg process to terminate
voice_client.stop()
await voice_client.wait_for('on_stop')
# Start playing the next track
voice_client.play(...)```
use that
what's the point of vnc
literally what's wrong with ssh
ids are integers, not strings so remove the quotes around it
well ssh is perfect if you dont mind the visuals
all ids or just the ones in the error message ?
the alert channel id
oh thanks
yoooOoooo sylestic my mans how you been
gud lmao
did you mean discord.Client.wait_for cause im getting voice client has not attribute wait_for
anyone only to help me locate an error in my bot ?
ill have it running for like 10 minutes and then it produces this error
future: <Task finished name='Task-13' coro=<schedule_videos_check() done, defined at /home/borderlessgaming/Desktop/Fox News Discord Bot/FoxNews.py:55> exception=AttributeError("'NoneType' object has no attribute 'send'")>
Traceback (most recent call last):
File "/home/borderlessgaming/Desktop/Fox News Discord Bot/FoxNews.py", line 57, in schedule_videos_check
await check_new_videos()
File "/home/borderlessgaming/Desktop/Fox News Discord Bot/FoxNews.py", line 43, in check_new_videos
await alert_channel.send(f"New Tucker Carlson video: https://www.youtube.com/watch?v={video_id}")
AttributeError: 'NoneType' object has no attribute 'send'
:incoming_envelope: :ok_hand: applied mute to @fresh ferry until <t:1678344866:f> (10 minutes) (reason: chars rule: sent 738 characters in 5s).
The <@&831776746206265384> have been alerted for review.
!unmute 977414482903072809
:incoming_envelope: :ok_hand: pardoned infraction mute for @fresh ferry.
🥹
It says that somewhere in your code you try to do None.send(...)
alert_channel was not found
Can you show some code?
:incoming_envelope: :ok_hand: applied mute to @fresh ferry until <t:1678345462:f> (10 minutes) (reason: chars rule: sent 1586 characters in 5s).
The <@&831776746206265384> have been alerted for review.
!unmute 977414482903072809
:incoming_envelope: :ok_hand: pardoned infraction mute for @fresh ferry.

im being targeted by the bot for sure
i sent source in your dms, im not gonna risk getting smacked by the bot again xD
fyi, you can use !paste when you need to send code without being smacked
Cause alert_channel is a tuple
With string as id
You need to pass id as int
While using the discord gateway and setting a desired ping interval that the HELLO message. provided it randomly turns off after a set amount of time and never stays online forever
whats the code?
Elaborate
should i delete the ' ' and that should make it an int?
show us your code on it
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1678347142:f> (10 minutes) (reason: chars rule: sent 204 characters in 5s).
The <@&831776746206265384> have been alerted for review.
!unmute 741194243930062861
:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.
ouch, @slate swan use '!paste' until the bot is fixed
Sorry. We're currently experiencing an issue with the bot that means you aren't able to post longer messages. It will be fixed momentarily.
just know that i create a websocket and on .run_forever i set the ping interval to 41.25 becauses thats what discor dprovided
need more info than just that, is it in a thread, is it asyncio based, how did you connect to it
well im at school so i can only provide code in 5-6 hours
show it once you're able to
The interval is based on provided info from discord
You don't decide it
Oh wait I misread
I am experiencing heavy intelligence level drop
relatable
make sure you're providing the correct sequence and OPCode while sending heartbeats to discord
doesn't run_forever acquire the main process tho? you wont be able to process any other information
Making discord API wrapper in java affected my braincells real hard
Even tho I was doing that like a year ago
in <module>
from discord_slash import SlashCommand, SlashContext
ModuleNotFoundError: No module named 'discord_slash'
im confused cause iv installed discord slash via pip install discord-py-slash-command
Use normal discord.py
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
i know this is a stupid question but what is the import statement for discord-py-interactions
import os
import discord
from discord.ext import commands, tasks
import googleapiclient.discovery
from discord_slash import SlashCommand
from discord_slash.utils.manage_commands import create_options, create_choice
cause i know this is wrong
hm? ping_interval handles itself but theres also an option called ping_timeout which i dont know how to setup
yeah 100000% lol its sad
ntents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
client = commands.Bot(command_prefix="/status", intents=intents)
this is what i need help with, i need to change it to work for slash commands and tree.commands is way outdated, anyway you guys can help me fix this last part and the rest will work
@tree.command(name='status', description='Check the status of the bot')
async def status(ctx):
await ctx.send(f'{client.user.name} is running and the YouTube API is working')
Why are you making two bot instances
Do not do this
And app commands use interactions and not contexts
Look in the pins
If you want the things to be a bit easier use disnake
anyone know the code for verify command?
what is a verify command
like you need verify before access more chat
looking at your about me i doubt u need it 
lol
hm
He's pro coder in phytonn not python
you mean when users have to accept the rules of the server?
that thing is only for guilds with the COMMUNITY feature enabled
i think he means like one of those captcha or click button to verify and get a role to acess channel bots
Yeah ig
Make a role that is allowed to view all the channels , like (role name ) “community” and for the default role “everyone” make 1 channel open that is the verification one so when the user reacts on message of verification just give him the “community” role and make sure to disable the “view channel perms” for the “community” role.
hi
Hello
is there anyway to make a command run every 24 hrs?
supposing the time doesnt reset even if the bot is restarted
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
oo
(Doesn’t reset If bot restarts)
Ig it does reset
You need to store the time u send then compare the time
Hope it helps
Why don't just use the time argument 
if the time is passed it does not execute
What does not execute
I want to make a DM message for welcome. A member joins, the bot sends a sweet message to them to welcome. I tried on_member_join event but it does not seem to work. Please tell me if there is some new way or am I wrong?
What does not work about it exactly
can anybody tell me why my bot only answers me back on private messages? i should everything set up correctly on the discord developer app. Im trying to make a moderator bot
my on_member_join event does not work
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
this appears on my terminal
Did you enable message_content intent
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
should i send you my code`?
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\HP Demo Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\HP Demo Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\HP Demo Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
File "C:\Users\HP Demo Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
File "C:\Users\HP Demo Machine\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 360, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
ah fudge
i deleted some of the content or else i couldnt send the message
@bold python Remove the homophobic slur from your code. See our #code-of-conduct
oh alr
anyone knows how i download this
!
Wait what is client.user in the discord bot code at the start? Is the user the one that interacts with the bot??
yep
Alright that makes sense
So in order to make the discord bot I need to use the input(), if statements and other stuff in order to have a user input?? Or is there special indicated functions that the discord library has that I need to learn/use
client.user represents the bot's user account
if you want to get a user input from discord, then you'll need to use a method from the library, yes
No
Alr
Bro is there a website to find all the functions inside of the discord.py library??
Like im clueless rn Idk what to do :/
It's called documents
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
like the name is just documents??
I already have a bot setup and everything. Im tryna figure out how to make it so when I say "Hello" it says hello back
This is the website with all the functions??
yeap
Not just
Where do I go then
It depends on what you want to find.
Yes, if you are a beginner and don't know where to start, this little instruction will help you
Yea I got that code setup
I put my token in it
intents.members = True
intents.guilds = True
intents.messages = True
token = ""
bot = commands.Bot(command_prefix='!', intents=intents)
# Bot ready event
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}!')
#en:
await ctx.send('I do not have permission to kick that member.')
else:
await ctx.send('I do not have permission to kick members.')
# Ban command
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
if ctx.me.guild_permissions.ban_members:
try:
await member.ban(reason=reason)
await ctx.send(f'{member} has been banned from the server.')
except discord.Forbidden:
await ctx.send('I do not have permission to ban that member.')
else:
await ctx.send('I do not have permission to ban members.')
# Command error handler
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('You do not have permission to use that command.')
elif isinstance(error, commands.MemberNotFound):
await ctx.send('That member was not found.')
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Please provide all required arguments.')
else:
print(error)
# Respond to messages event
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content == "Hi!":
response = f"hi, {message.author.mention}!"
await message.channel.send(response)
await bot.process_commands(message)
print(f'Received message: {message.content}')
why is my bot not responding back to me on my server only on private message
it should be all correct on the discord Developer website.
I deleted some code that had nothing to do with the message stuff cause i had to many words and couldnt send it, But i believe the code has all thats needed to write me back. I jsut dont understand why he wont write back at me. He has all the rights and is allowed to text and all that
You need intents.message_content
so like under the other intents codes that i have $
do i have to do = True at the end or only write the intents.mes....
It works thanks bro .
Hello guys, i need help with working with tasks on discord bots
And
i currently have a task which gets initialized from a bot command. I'm still testing the command so it looks something like this:
@bot.command()
async def ban_till(ctx, user: discord.Member,interval: int = 300,*,args):
print("Got ran to ban user")
await asyncio.sleep(10)
MyTask(ctx,user.id,interval)
This is the class the tasks is encapsulated in:
class MyTask:
def __init__(self,context,user,interval) -> None:
self.context = context
self.user = user
self.interval = interval
self.start_task.start()
@tasks.loop(count=1)
async def start_task(self):
db = DbWriteHandler(table="banned_user",writer=insert_banned_user(self.user,self.interval,1),to_delete=delete_banned_user(self.user))
write_db = await db.write_to_table()
print(write_db)
if write_db == True:
await asyncio.sleep(int(self.interval))
try:
print("Got here")
await self.context.guild.unban(self.user)
check_delete = await db.delete()
print("Got deleted")
if check_delete:
print("successful")
else:
raise ValueError("Database Object Could not be deleted")
except Exception as e:
print("exception triggered")
await self.cancel_task()
print("Got here after stopping task")
else:
raise ValueError("Could not write to DB")
# @start_task.after_loop
async def cancel_task(self) -> None:
self.start_task.stop()
Should i be changing the logic of the implementation. Right now the code is hitting the Exception which i want but it doesn't stop the task after it hits the Exception. I need to be able to stop the task
Loop.stop() stops the task from looping after the current iteration is complete, but this won't have any effect here since you're only running the task once anyway.
On the other hand, cancel() cancels the task without letting the current iteration finish, so it may be what you're after, unless I'm interpreting the question wrong.
The issue is not with that, i already tried to cancel the task without awaiting it as i should. So in the exception block where i have self.cancel_task() I just do self.start_task.cancel() without awaiting as i should but the code reaches there and passes through it to the print statement after it and just holds the thread without exiting the function. When i check the logger, i don't get any errors except when i use an await, then the logger prints an error to not use an await but apart from that, i'm not getting any errors to be able to debug. And when i do a KeyboardInterrupt i don't get any errors in the terminal. So i can't find where the issue is
tasks.loop stop automatically when an exception occur btw no need to stop it yourself
After the exception is it, i would need to run some functions so i have to capture the exception and then cancel after i run the functions i need run. But right now, without even doing anything in the exception, the thread doesn't get cancelled, it just gets held until i do a KeyboardInterrupt
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 370, in _scheduled_task
await item.callback(interaction)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\user_moderation\view.py", line 155, in callback
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 866, in send_message
await adapter.create_interaction_response(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 184, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
Errror ^
Code Part 1 ⤵️
https://paste.nextcord.dev/?id=1677938097326479
Code Part 2 ⤵️
@warn.subcommand(name="edit-by-user")
async def warn_edit_by_user(self, inter: nc.Interaction,
member: nc.Member = SlashOption(name="member", description="Please select a member", required=True)):
async with aiosqlite.connect("maja.db") as db:
async with db.cursor() as cursor:
await cursor.execute('SELECT case_id FROM warn_system WHERE user_id = ? AND guild_id = ?', (member.id, inter.guild.id,))
cases = await cursor.fetchall()
if cases:
options = []
for case_id in cases:
await cursor.execute('SELECT reason FROM warn_system WHERE case_id = ? AND guild_id = ?', (case_id[0], inter.guild.id,))
reason = await cursor.fetchone()
new_option = nc.SelectOption(label=f"CASE: {str(case_id[0])}", description=f"REASON: {reason[0]}")
options.append(new_option)
options = options[:25]
i_embed = nc.Embed(title=f"Warnings from {member}", description="Please select a warning to edit it", colour=config.blurple)
dropdown = EditWarnDropdown(member, options)
await inter.response.send_message(embed=i_embed, view=dropdown, ephemeral=True)
else:
notfound_embed = nc.Embed(title=f"No Warnings found", description=f"I couldn't find any strikes for {member}", colour=config.blurple)
await inter.response.send_message(embed=notfound_embed, ephemeral=True)```
pretty sure its raising an error since loop.stop isnt a coroutine and you're awaiting it, when an error occur in a task similar to asyncio.Task, it gets silenced and stop the task, it doesnt 'held' it.
!d discord.ext.tasks.Loop.error
@error```
A decorator that registers a coroutine to be called if the task encounters an unhandled exception.
The coroutine must take only one argument the exception raised (except `self` in a class context).
By default this logs to the library logger however it could be overridden to have a different implementation.
New in version 1.4.
Changed in version 2.0: Instead of writing to `sys.stderr`, the library’s logger is used.
use this to capture that error
you may wanna use Loop.cancel instead if you wanna cancel it abruptly
yeah, i already removed the await, because i was getting an error because its a NoneType, but even without an await it still just holds the thread
i already tried cancel and then did stop, both doesn't exit the thread. Have thought about the fact maybe its the bot_command still holding the thread but when i make a print function in the bot_command after calling the class, it doesn't get there. So the thread is stuck in the task still
um what are you even using to create the websocket connection, mind sharing your code?
how does it "hold" the thread may i ask? what does it print, where does it stop printing
it seems i have been overcomplicating the issue, just realised that
um oke
so i think i get what the issue is, After the bot_command calls the task, it seems it can execute any other code after that task so, a print statement after that task won't be run after it starts the task
!d nextcord.ui.StringSelect
class nextcord.ui.StringSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI string select menu.
This is usually represented as a drop down menu.
In order to get the selected items that the user has chosen, use [`StringSelect.values`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ui.StringSelect.values "nextcord.ui.StringSelect.values").
There is an alias for this class called `Select`.
New in version 2.0.
@white citrus I believe you need to subclass that ^ instead of Select
Although not sure, callbacks implementation in this case is kinda confusing imho
A Python wrapper for the Discord API forked from discord.py - nextcord/dropdown.py at stable · nextcord/nextcord
They stole my example
/s
can I have help moving my slash commands into their own files
cogs
Seems like outdated
which ones were urs?
!d nextcord.ui.Select
alias of StringSelect
A it's an alias my bad
Drop-down and modal
oh noice
God knows what
wish there was a inbuilt way to wait for modals to be submitted
You mean like our implementation in bobux bot?
idr that but like
await inter.response.send_modal(Modal())
# wait for modal to be submitted
# do some stuff then
Yeah it is like that
oh well then like that :p
Callback?
Probably would be better to set _fut in init tho
Problem of callbacks is they split code into several parts and make it harder to navigate
callback is called after submission
Wait for callback
i might want to deal with my current view
Ohh
That's why we have GenericView class and custom Modal (formerly BadModal) in bobux bot 🤓
I think I brought those things out to my template
Bobux bot
Bobux bot
interaction._state._modal_store.remove_modal(interaction.author.id, interaction.custom_id)
whats this for?
cliff hanger
@vale wing
Bobux Bot is a funny name, what does it do?
It's an economy bot
infinite Bobux
it gives robux
what discord.py gives you (or in your case nextcord) is a proxy over the actual field so setting its value wont do anything
@slate swan you should use set_field_at() instead and enumerate over the fields to get the corresponding index, or alternatively re-create the entire embed each time
A line to fix disnake's internals behaving dumb
i tried without that it worked fine with that it raised a key error tho
apparently didnt find the key while popping
That thing could've gotten fixed in last updates
That was actual for 2.7, not sure if it is required now
Need to test some commands that use that modal
ic
@shrewd apex actually the problem was disnake would automatically mark modal interaction as responded if it wasn't responded in callback
And that line prevents it from doing that
So if you respond in callback you don't need that line
And that issue persists
That's one of disnake's main advantages over dpy with interaction.response.send_message
You can check the link in my bio, there's info about what bot does and who developed it
Yeah the events and classes separation is quite convenient
it might be stupid but why it says undefined name 'member and ctx?
only on this line
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
guys real quick. There is still no possible way for a Bot to join a Voice channel on his own right ?
Like not even by maybe rjeoining a person on its own
of course there is you just need to tell him to which and when
but i mean like this. A person joins a voice channel. And the bot joins his voice channel aswell but on its own, Without anyone typing /join or whatever.
That thing always existed?
Realy?
so when someone joins voice the bot joins the voice as well?
Except it was once moved from on_member_update to on_voice_state_update or smth, I don't remember exact event name
Bro i could swear a bot could not join on his own, Cause like a music bot cant join or play music unless u are in the channel aswell right. SO i thought there was no way
!d discord.on_voice_state_update surprisingly I remember it correctly
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
and btw you guys keep on makin my life harder cause i kept askin bout youtube bot help and shi like that. But what about spotiy bot. After all Youtube was the one with beef not spotif. RIght ?
Does spotify have API that allows you to stream audio? I suspect it does not
I dont know
Soundcloud had some issues with getting API key when I last tried
You had to like send them a google form which was closed 🗿
yh but the whole yt shi also complicated atm. The last update they had for youtube.dl was 2021
and yt.dlp aint workin with me so i just gave it up ill try again later once i know some more stuff about coding and all.
Actually what for would you need youtube bot? Discord's got youtube activity now
yh true. But i dont know. Just like it used to be back in the days. With some music bot playin some cs. But at the end of the day. I woudltn even use my own bot. From what i know my laptop would need to be on, using internet, For the bot to keep runnning. And that would just be a pain.
But i guess i wasnt rly after a music bot, cause there are still plenty out there, it was more the desire to be able to make one that i was chasing. Knowing that i myself was able to create a music bot is rly what i wanted to achieve.
but how or where would i put this code?
@bot.event
async def on_voice_state_update(member, before, after):
# my code here?
Similar
async def on_voice_state_update(member, before, after):
if before.channel != after.channel:
if after.channel is not None and 'my_role_name' in [role.name for role in member.roles]:
# Join the voice channel
await after.channel.connect()
If you help us make a site for it sure 😃
ahaaaa and thars not illigal or what ? XDXD
What
my yt bot highly illigal but infinite robux
Infinite bobux is legit
bobux?
Meme crypto
ah i tought yall ment robux from roblux or some
nvm i go check the code see if it works
class carwsd(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def rank(ctx, member:nextcord.Member):
a = RankCard(
settings=Settings,
avatar=member.display_avatar.url,
level=1,
current_exp=1,
max_exp=1,
username=f"{member.name}#{member.discriminator}"
)
image = await a.card3()
await ctx.edit_original_message(file=disnake.File(image, filename="rank.png"))
def setup(bot):
bot.add_cog(carwsd(bot)) ```
```nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'display_avatar'
The error message suggests that there is an AttributeError in the command being invoked and that the 'Context' object has no attribute 'display_avatar'.
It's likely that you have a command that is using the .display_avatar attribute, but that attribute doesn't exist in the Context object. Double-check your code and make sure that you are using the correct attribute for the Context object.
If you are still unsure what the issue is, you can post the code for the command that is causing the error, and I can help you debug it.
Thank you so much ill check
class carwsd(commands.Cog):
def init(self, bot):
self.bot = bot
@commands.command()
async def rank(self, ctx, member:nextcord.Member):
a = RankCard(
settings=Settings,
avatar=member.display_avatar.url,
level=1,
current_exp=1,
max_exp=1,
username=f"{member.name}#{member.discriminator}"
)
image = await a.card3()
await ctx.edit_original_message(file=disnake.File(image, filename="rank.png"))
def setup(bot):
bot.add_cog(carwsd(bot))
try this
Lmk if the code i sent above still errors
thanks! now sadly saying that
if isinstance(self.avatar, str):
if self.avatar.startswith("http"):
self.avatar = await RankCard._image(self.avatar)
else:
raise TypeError(f"avatar must be a url, not {type(self.avatar)}") ```
``` File "c:\Users\PC\Desktop\Aleccy Bot\cogs\card.py", line 109, in card3
self.avatar = await RankCard._image(self.avatar)
AttributeError: type object 'RankCard' has no attribute '_image'```
ok 1 sec
async def _image(url: str):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return io.BytesIO(await response.content.read())
This method downloads the image from the URL and returns it as a BytesIO object.
Once you have defined the _image method, you can call it with await self._image(self.avatar) instead of await RankCard._image(self.avatar) in your code.
File "c:\Users\PC\Desktop\Aleccy Bot\cogs\card.py", line 123, in card3
background = self.background.resize((1000, 333))
AttributeError: 'member_descriptor' object has no attribute 'resize'```
@client.tree.command(name="avatar", description="Gets an user's avatar.")
async def avatar(interaction: discord.Interaction, member:discord.Member = None):
if member is None:
member = interaction.author
else:
embed = discord.Embed(title=member.name + "#" + member.discriminator)
embed.set_image(url=member.avatar.url)
await interaction.response.send_message(embed=embed)
I am trying to make the bot get the person's avatar, when I put which member's it'll work but when I put none it doesn't send the author's profile picture... what mistake did i made?
im very sorry for asking all these qquestions
NoaA i send you a private dm real quick i show u smt
you don't need the else block
Oh
your current logic is ```py
if member is None:
# assign author to the member variable
else:
# send embed
if member will be None, it will just assign the var and do nothing
I tried removing it but i got this instead
show updated code
@client.tree.command(name="avatar", description="Gets an user's avatar.")
async def avatar(interaction: discord.Interaction, member:discord.Member = None):
if member is None:
member = interaction.author
embed = discord.Embed(title=member.name + "#" + member.discriminator)
embed.set_image(url=member.avatar.url)
await interaction.response.send_message(embed=embed)
yep it has no attribute author
I am actually so stupid
let's see if that resloves the issue
Yeah it now works, thanks alot for correcting me man!
no problem!, py embed = discord.Embed(title=member.name + "#" + member.discriminator) can be shortened to ```py
embed = discord.Embed(title=str(member))
str of a Member object gives username#discriminator
OHH
why am i getting a problem report from a message that should even rly be part of the code??
it doesnt go away but i didnt have it before. I jsut appeared after i wrote @bot.event
it needs a function after @bot.event decorator
so it gives error since there is no function bellow
how i can fix that i never got this bfore
can you send me copyof the error message and code, like a physical one i can copy
just copy paste
raceback (most recent call last):
File "main.py", line 1, in <module>
import nextcord as discord
File "/home/runner/lounge/venv/lib/python3.10/site-packages/nextcord/init.py", line 23, in <module>
from . import abc, opus, ui, utils
File "/home/runner/lounge/venv/lib/python3.10/site-packages/nextcord/abc.py", line 5, in <module>
import asyncio
File "/home/runner/lounge/venv/lib/python3.10/site-packages/asyncio/init.py", line 21, in <module>
from .base_events import *
File "/home/runner/lounge/venv/lib/python3.10/site-packages/asyncio/base_events.py", line 34, in <module>
from . import tasks
File "/home/runner/lounge/venv/lib/python3.10/site-packages/asyncio/tasks.py", line 567
fut = async(arg, loop=loop)
^^^^^
SyntaxError: invalid syntax
thats what i got
try this ```fut = asyncio.ensure_future(arg, loop=loop)
try that above
yeah
also i tried to do a level system and everytime sm1 send a message this error appear
can you send me the error again like last time?
and btw did the last one hekpo the lsat code?
yeah its fixed
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/lounge/venv/lib/python3.10/site-packages/nextcord/client.py", line 490, in _run_event
await coro(*args, **kwargs)
File "main.py", line 688, in on_message
users = json.load(f)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/init.py", line 293, in load
return loads(fp.read(),
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/init.py", line 346, in loads
return _default_decoder.decode(s)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) and this is what i go
can someone help me move my discord.py slash commands into their own respective files
use cogs
I am confused on how
I am using slash commadns
yeah, that's not a problem
can you help me through
you could also just use https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html, but i'd recommend using cogs
I have done similar stuff with javascript before
ok
can I ask you if I have any questions
just ask here, if im not able to help then someone else will most likely help you
I have a bunch of commands
and
I dont wanna have to load each one the way it is demonstrated in the article. It will make my code look just as bad
This is not like js( i mean cogs)
Loop through it
well luckily we have loops
@client.event
async def on_ready():
print(f"Logged in as {client.user.name}")
try:
for filename in os.listdir('./cmds'):
print("Checking for commands")
if filename.endswith('.py'):
print(f'commands.{filename[:-3]} loaded')
await client.load_extension(f'commands.{filename[:-3]}')
except:
print("No commands were synced")
Yea but don't use it on on_ready event
Use setup_hook event instead
are you syncing your commands?
slash commands needs to be synced
yeah I am
where?
my bot was working before
I am trying to sync them after moving them now
that is what I want help with
Also I don't think client support cog
also, do I move this part where I define the slash command to it's respective file with it? py @client.tree.command(name="hello", description="Become friends with this bot :)")
Ig you need to use bot instead of client
I call it client
Oh right
but I use the Bot subclass
client = commands.Bot(command_prefix = "!", intents=intents)```
are you trying to create slash commands in cogs?
yes
any1 could help w that error?
i'll assume you're aware how cogs work usually, right?
kinda
You should use
@app_commands.command() decorator in cogs if i remember correctly(for slash commands)
ok
so the way you create slash commands is almost same, you'll just be using app_commands.command decorator instead of tree.command
class MyCog(commands.Cog):
@app_commands.command(name="ping", description="pong!")
async def ping(self, inter: discord.Interaction) -> None:
...
``` the first argument will always be `self` since it;s a method inside a class
discord.py will load the command as you load the cog automatically, like it does for prefix cmds
so does load_extension() sync it?
No
load_extension just load the cogs you need to sync it manually
dang I accidentally removed the sync part of my on_ready event
it just loads it into the tree, you still gotta sync it manually
what is the function to sync commands again
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
do I do like client.tree.sync
perfect
lol the command I moved to it's own file still does not load
@slate swan
how did you create it, show code
this is the code for the command ```py
import discord
from discord import app_commands
@app_commands.command(name="hello", description="Become friends with this bot :)")
async def hello(interaction: discord.Interaction):
interaction.response.send_message(f"Hello {interaction.user}", ephemeral=True)```
@client.event
async def on_ready():
print(f"Logged in as {client.user.name}")
try:
for filename in os.listdir('./cmds'):
print("Checking for commands")
if filename.endswith('.py'):
print(f'commands.{filename[:-3]} loaded')
await client.load_extension(f'commands.{filename[:-3]}')
await client.tree.sync()
except:
print("No commands were synced")```
Is this in a cog or main file
And you need to await the coroutine
!d discord.app_commands.CommandTree.add_command (test)
add_command(command, /, *, guild=..., guilds=..., override=False)```
Adds an application command to the tree.
This only adds the command locally – in order to sync the commands and enable them in the client, [`sync()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.sync "discord.app_commands.CommandTree.sync") must be called.
The root parent of the command is added regardless of the type passed.
yeah so just create a setup function in the extension file, and use bot.tree.add_command there
dont sync for every iteration
I dont lol
that won't be a cog but you will be able to seperate your commands into diff file
for filename in os.listdir('./cmds'):
print("Checking for commands")
if filename.endswith('.py'):
print(f'commands.{filename[:-3]} loaded')
await client.load_extension(f'commands.{filename[:-3]}')
await client.tree.sync()
you do
This is how you use cogs
Also add function called setup at end of you code then add cogs like example
I am so confused
Extensions and cogs are different
I just want to be able to put my slash commands into their own respective files
Read this first.
Extension are the files that you actually loads. when you load an extension by using load_extension
Setup function will be called
Then also read this
https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html
Instead of adding command in setup function you can add cogs( basically using cogs with extensions)
Also if you just want to create 1 command per file then just use extension
that is exactly what I want to do
So this
but how do I register the extension
i got this error when sm1 type a message in the server for the leveling system
I already have done what that article says
What do you mean by registering? Syncing slash command?
yeah
.
I have this @client.event async def on_ready(): print(f"Logged in as {client.user.name}") try: for filename in os.listdir('./cmds'): print("Checking for commands") if filename.endswith('.py'): print(f'commands.{filename[:-3]} loaded') await client.load_extension(f'commands.{filename[:-3]}') client.tree.sync() except: print("No commands were synced")
but the command that is in it's own file does not register
?
Hmm idk about that but don't do anything in on_ready use setup_hook event instead
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
when I replace on ready with it my bot just stops
@client.event
async def setup_hook():
print(f"Logged in as {client.user.name}")
try:
for filename in os.listdir('./cmds'):
print("Checking for commands")
if filename.endswith('.py'):
print(f'commands.{filename[:-3]} loaded')
await client.load_extension(f'commands.{filename[:-3]}')
client.tree.sync()
except:
print("No commands were synced")```
i have no idea
Dam
Also don't auto sync bc every time you run your bot tree get synced you only need to sync when you update an command
it works now
I just still have not been able to sync
@tired pollen it runs now I dont know why it did not that one time
I can't send DMs to my bot.
It gives me a captcha to complete, the gives me the usual Clyde "You cannot send a message to this user, this is usually because you do not share a server with this user..."
But I do share a server with the bot
Would it have something to do with having a VPN active?
Mm
I don’t think it has anything to do with a vpn
Does the bot dm you first?
@pulsar bridge
Nope
I fixed it by sending it a DM from a Non-VPN connected device, so I assume it has something to do with VPNs 🤔
Why aren’t you using slash commands
Also try sending code formatted messages instead of screenshots
And include the section of code causing the error for future reference
you shouldn't sync in setup_hook
Do I just run sync whenever I add a new command
And where do I run it @smoky sinew
make a message command
There is no disadvantage
on_ready can be called multiple times during the bots running
you would also get ratelimit due to the syncing, especially global sync ones, that is a disadvantage
Why do some people still use requests instead of aiohttp?
What are the advantages of using requests?
requests is used if your codebase isn't asyncio based
thats just it tbh, its a sync library, aiohttp is the asyncio alternative
You should be using aiohttp if you're working with a Discord bot
Why not?
because sometimes cogs aren't loaded by then
The load_extension calls are happening before the sync
yes
and if you restart your bot often you're going to get ratelimited without changing any commands
because you are sending requests to the api for identifying the bot
not just commands.
in fact multiple requests are sent at startup as well as heartbeat
with what
yes!
why /s
thanks
I would call them webhook payloads
Iirc you can send 1000 Identify calls once per day or something
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Ignore. Was trying to make a bad joke, lol
I feel ya Robin
how are they able to implement slash cmd in a webhook?
Not possible
That's common slash command wdym 🗿
what , the webhook is responding on a slash command
Mm why are you so confident about that

Well at least not with the type of webhooks that we know of
its a webhook btw...
look at this , when i type / in the chat it shows the webhook with a slash cmd named finish. btw there is no bot named Aizen
I'm not sure but maybe it has something to do with followup
ok no this is false
Looking at the context it is a service that allows you to obtain developer badge. I assume it creates an appication for you and allows you to use a slash command to get the badge, then deletes it. It's probably just a deleted application, not a webhook
Sorry i was sleep
You are looping through cmds directory right?
For loading cog you should pass file name like that
directoryName.filename[:-3]
What does filename[:-3] means is the file name without .py.
you are looping through cmds directory so in load_extension you should pass cmds.fileName[:-3] not commands.fileName[:-3]
hello i need help
im shifting from nextcord to discord and im making a slash command for banning members
and interaction.response dont have send_message
@light violet actually I just read the docs, it seems you can register application commands without creating bot account, but that's nothing related to webhooks
Do you need the way of doing that or you're just interested
What are you talking about
its fixed no worries
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
thanks btw
!code

!d time.sleep
time.sleep(secs)```
Suspend execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time.
If the sleep is interrupted by a signal and no exception is raised by the signal handler, the sleep is restarted with a recomputed timeout.
The suspension time may be longer than requested by an arbitrary amount, because of the scheduling of other activity in the system.
Working lol
I accidentally posted my bot token in my python module. but the discord system has detected and reset it. never knew that and I was gonna find out the hard way properly 💀
idk how that happend it was in tests folder
Nice
how to do like if there is discord.ext.commands.errors.MemberNotFound: then dont throw error instead send message in a channel
explain...
discord.ext.commands.errors.MemberNotFound: Member "69420" not found.
it throws error i dont want that
on command error event could do that
yea
on_commmand_error
if isinstance(error, errorName):
what to do```
how to purge messages in a cog
!d discord.discord.ext.commands.on_command_error
discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArguments):
# Replace MissingRequiredArguments with your error
ctx.send("Please pass all required arguments")
here an example. you would need to import the error
Here is an example ```py
@Cog.listener('on_command_error')
async def err_handler(self, ctx: Context, error: Any) -> None:
# if command has local error handler, return
if hasattr(ctx.command, 'on_error'):
return
# Get original error instead of a global Invoke error
error = getattr(error, 'original', error)
# Standard debug to log to catch unknown errors
logger.debug(type(error))
if isinstance(error, CommandNotFound):
logger.debug(f"{ctx.author} this command does not exist")
elif isinstance(error, HTTPException):
error.text = error.text.replace("\n", " ")
logger.warn(f"HTTPException: {error.text}")
elif isinstance(error, NotFound):
error.text = error.text.replace("\n", " ")
logger.warn(f"NotFound: {error.text}")
elif isinstance(error, CheckFailure):
logger.debug(f"Check failed for {ctx.author} most likely has no permission to execute this")
else:
logger.error(error)
slash command
don't you feel it's abit complex hm?
no one?
yaa
hold on
ok ok
Get channel and then use purge method?
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.checks.bot_has_permissions(manage_messages=True)
@app_commands.describe(count="Number of messages to delete")
async def clear(self, interaction: discord.Interaction, count: int):
await interaction.channel.purge(count)```
this not work
I have this old code
async def setup(ctx: commands.Context):
dm_channel = await ctx.author.create_dm()
welcome_embed = discord.Embed(title='Welcome to the setup',
description='Thank you for purchasing.\n\nLet\'s run you through the steps to setup Automatic Boosts through SellApp or Sellix!\n\nFirst, please choose which one you\'ll be using.',
color=discord.Color.blue())
sellapp_button = discord.ui.Button(label='SellApp', style=discord.ButtonStyle.primary, custom_id='sellapp')
sellix_button = discord.ui.Button(label='Sellix', style=discord.ButtonStyle.primary, custom_id='sellix')
button_row = discord.ui.Row(sellapp_button, sellix_button)
welcome_embed.add_field(name='\u200B', value='\u200B', inline=False)
welcome_embed.set_thumbnail(url='https://assets.umod.org/images/icons/plugin/624057848f3f2.png')
await dm_channel.send(embed=welcome_embed, components=[button_row])
the way its setting up the buttons right now isn't correct
I saw that you need classes and stuff for it but I don't really know if it's possible to implement it in this code
no errors?
@client.command()
async def check(ctx, user: discord.Member):
query = {"userid": user.id}
result = enrolled.find_one(query)
if result:
await ctx.send(f"{user.name} is in the database")
else:
async def on_command_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
return
await ctx.send("User not found")
what about this???
NOOOOOO
We gave two examples.
that's not how it works. try the examples above
@client.command()
async def check(ctx, user: discord.Member):
query = {"userid": user.id}
result = enrolled.find_one(query)
if result:
await ctx.send(f"{user.name} is in the database")
@check.error
async def check_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("User not found")
@slate swan
How old is your bot 🗿
Some of this code has been deprecated for years.
help me
I searched about the problem no results were found. i would need to try it manually. can you paste your bot code if you dont mind
This is possible but for an error like that I recommend a global one.
yea i know
i wanted to be fast right now so his problem gets solved
Any errors?
naah
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.checks.bot_has_permissions(manage_messages=True)
@app_commands.describe(count="Number of messages to delete")
async def clear(self, interaction: discord.Interaction, count: int):
await interaction.channel.purge(count)```
I know but then he/she is going to run into problems later.
Do you have error handler eating you errors?
me?
Yes
yes
old
but how would I implement the buttons?
in a different cog
if isinstance(error, app_commands.MissingPermissions):
confEmbed = discord.Embed(title="ERROR!", color=discord.Color.red())
confEmbed.add_field(name=f"{error}",
value=f"Ohhhh! I don't this you have permissions to do that.",
inline=False)
await interaction.response.send_message(embed=confEmbed, ephemeral=True)
if isinstance(error, app_commands.BotMissingPermissions):
confEmbed = discord.Embed(title="ERROR!", color=discord.Color.red())
confEmbed.add_field(name=f"{error}",
value=f"Maybe the owners didn't gave me the permissions. :cry:",
inline=False)
await interaction.response.send_message(embed=confEmbed, ephemeral=True)```
rows have been deprecated for a long time
any new way?
it worked but it throws error in terminal
what is it
can you send it?
Here's an exmaple on how to make it with discord.py https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py
@shadow vigil my error handler for msg purge'
Oh actually limit=count
You basically have this View called Confirm and that gets passed inside a send() function.
ohhhhh
discord.ext.commands.errors.MemberNotFound: Member "594541" not found.
oh bruh how did not see that
Lol idk
But that shouldn't give any issues and still delete 100 messages.
i thought it only took 1 arg so i just did it without limit
and +1 so he delete your msg + amount
hey it worked but........
hm
it said this "The application did not respond"
When you run that you will get error says purge only take 1 positional arg( which is self)
Now that I think about it you can overengineer the crap out of the purge it can do so much.
Hmm true, prob his error handler being weird.
Yea
only that?
yaa
Put an else after your if statement and raise any other error@fresh fern so your error handler don't eat errors
o ok
else:
what in else
raise error
raise error
ok ok
Or whatever you called error
You passed error as arg right?
it gonna raise the error. example
yea yea
It can be anything
still it said that'
!e
raise TypeError("just an example")
@shadow vigil :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | raise TypeError("just an example")
004 | TypeError: just an example
You didn't respond then
what should i respond in purge
response
Cleared X amount of message or smth.
ok i thought that purge should be secret
Ephemeral.
Actually you need to response to an interaction or will give you application does not response or something like that
oh yea
ohh
That's will not raise error but on discord it says that
I do recommend making it defer since sometimes it can take a bit longer than 3 seconds.
Response to an interaction by defering it or
!d discord.InteractionResponse.send_message
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
whats defer
Yea that
This is defer
I can't click these buttons it just says interaction failed
my code:
class Ask(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label="SellApp", style=discord.ButtonStyle.primary)
async def sellapp(self, button: discord.ui.Button, interaction: discord.Interaction):
self.value = "sellapp"
self.stop()
@discord.ui.button(label="Sellix", style=discord.ButtonStyle.primary)
async def sellix(self, button: discord.ui.Button, interaction: discord.Interaction):
self.value = "sellix"
self.stop()
@client.slash_command(name='setup', description='Set up through SellApp or Sellix')
async def setup(ctx: commands.Context):
dm_channel = await ctx.author.create_dm()
welcome_embed = discord.Embed(title='Welcome to the setup',
description='.',
color=discord.Color.blue())
welcome_embed.add_field(name='\u200B', value='\u200B', inline=False)
welcome_embed.set_thumbnail(url='https://assets.umod.org/images/icons/plugin/6240')
view = Ask()
await dm_channel.send(embed=welcome_embed, view=view)
await view.wait()
if view.value == 'sellapp':
platform = 'SellApp'
elif view.value == 'sellix':
platform = 'Sellix'
else:
print(view.value)
await dm_channel.send('Sorry, something went wrong.')
return
apikey_embed = discord.Embed(title=f'Please provide your {platform} API key',
description=f'You can find your {platform} API key by following the steps {platform} has provided on their site.',
color=discord.Color.blue())
await ctx.send(embed=apikey_embed)```
Actually that message says
Bot is thinking...
Defer is so you respond within the 3 second window but you can take actions later like edit a message for instance. You can use discord.Interaction.followup trough a webhook to also send new messages.
ohhhhh
Not by default but yeah can make that work.
Yea right or you can edit it later with edit_original_response method
Not really since defer doesn't send a message so there is nothing to edit.
ik that don't send message but you will have access to original res
Yep.
i can relate
could anyone help me?
hey my code is working but an error is thrown in terminal
shall i use try - expect? will that work?
here
Is this indention correct?
yes
Have you setup the global handler or are you having trouble with it?
i dont have any global handler
Give code
@client.command()
async def check(ctx, user: discord.Member):
query = {"userid": user.id}
result = enrolled.find_one(query)
if result:
await ctx.send(f"{user.name} is in the database")
@check.error
async def check_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("User not found")
raise error
Bro remove raise error
You also asked this a day ago or so. We gave you exactly the same response now, I recommend doing some research on the examples we send and docs.
It always raise error no matter what happened if you want to get errors except member not found put an else statement and then raise error on else
That's actually means if error is an instance of memberNotFound class return true otherwise return false
Also idk how much discord.py likes it if you overwrite a function with this one.
So if error is instance of MemberNotFound error then it will handle error if it's not then raise the error .
Well ig that's not hard?
Just ask your questions
i didnt understand that
you mean this?
@client.command()
async def check(ctx, user: discord.Member):
query = {"userid": user.id}
result = enrolled.find_one(query)
if result:
await ctx.send(f"{user.name} is in the database")
@check.error
async def check_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("User not found")
else:
raise error
Yes exactly
If error is not member not found then it will raise the error
Just do,
return await ctx.send(..)
so you dont need else statement
didn't work my bot send the message in the channel but errors is still getting thrown in terminal
Its actually the same not much difference
Interesting
The error is member not found?
if isinstance (.....):
return await ctx.send("User not found")
raise error
Can you try this?
Well , same result
It shouldn't
Maybe he has global error handler
Yea
wait lemme share my full code
i have this also
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
return
raise error
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.DisabledCommand):
return await ctx.send("This command is disabled.")
raise error```
Or just basic Python in general
2 command error event? 💀
Well , that will work but ig elif is better way?
iirc you can have only one same event with .event and can have multiple same event with .listen()
It won't work, the first event will never trigger
Oh yea actually i forget
So if you want to have 2 command error event you should register one of them by event decorator then with listen decorator you can listen to it right?
Actually not 2 command event


What’s ur questi n
Nothing solved i was thinking how to listen to 2 command error event
there is event that is called on any command error
0|blitzcrank | [2023-03-10 12:54:01] [ERROR ] discord.ext.tasks: Unhandled exception in internal background task 'update_elo_ratings'.
0|blitzcrank | Traceback (most recent call last):
0|blitzcrank | File "/home/blitzcrank/.local/lib/python3.10/site-packages/discord/ext/tasks/__init__.py", line 239, in _loop
0|blitzcrank | await self.coro(*args, **kwargs)
0|blitzcrank | File "/home/blitzcrank/blitzcrank.py", line 60, in update_elo_ratings
0|blitzcrank | elo_rating = await calculate_mmr(summoner_id, RIOT_API_KEY)
0|blitzcrank | File "/home/blitzcrank/blitzcrank.py", line 104, in calculate_mmr
0|blitzcrank | participant_tier_and_rank = await get_tier_and_rank(participant['summonerId'], RIOT_API_KEY)
0|blitzcrank | File "/home/blitzcrank/blitzcrank.py", line 235, in get_tier_and_rank
0|blitzcrank | print(entry)
0|blitzcrank | UnicodeEncodeError: 'latin-1' codec can't encode characters in position 217-218: ordinal not in range(256)```
Help
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
code?
async def get_tier_and_rank(summoner_id, RIOT_API_KEY):
# Create a dictionary to map the rank strings to numbers
rank_mapping = {'I': 1, 'II': 2, 'III': 3, 'IV': 4}
# Use the API to get the summoner's league entries
url = f"https://euw1.api.riotgames.com/lol/league/v4/entries/by-summoner/{summoner_id}"
headers = {'X-Riot-Token': RIOT_API_KEY}
async with aiohttp.ClientSession(headers=headers) as session:
async with session.get(url) as response:
data = await response.json()
# Find the league entry for the RANKED_SOLO_5x5 queue
for entry in data:
print(entry)
if entry['queueType'] == 'RANKED_SOLO_5x5':
tier = entry['tier']
rank = entry['rank']
break
else:
# If no RANKED_SOLO_5x5 entry was found, return "Unranked"
return "Unranked"
# Capitalize the first letter of the tier
tier = tier.capitalize()
# Get the rank from the rank mapping
rank = rank_mapping.get(rank)
return f"{tier} {rank}"```
try to change print(entry) to print(entry.encode("utf-8"))
I don't think this is where the error came from

error message says its at print 
Oh yeah, I'm probably going blind
0|blitzcrank | print(entry.encode('utf-8')) 0|blitzcrank | AttributeError: 'dict' object has no attribute 'encode'
hm right cause this is dict
I never think printing should be where errors will ever come from
I tried print(str(entry).encode('utf-8'))
And I think it's okay forn ow
okay then
I added a print statement to see why the code breaks after a while
Here is the error from last night:
0|blitzcra | File "/home/blitzcrank/.local/lib/python3.10/site-packages/discor d/ext/tasks/__init__.py", line 239, in _loop
0|blitzcra | await self.coro(*args, **kwargs)
0|blitzcra | File "/home/blitzcrank/blitzcrank.py", line 60, in update_elo_rat ings
0|blitzcra | elo_rating = await calculate_mmr(summoner_id, RIOT_API_KEY)
0|blitzcra | File "/home/blitzcrank/blitzcrank.py", line 104, in calculate_mmr
0|blitzcra | participant_tier_and_rank = await get_tier_and_rank(participant ['summonerId'], RIOT_API_KEY)
0|blitzcra | File "/home/blitzcrank/blitzcrank.py", line 235, in get_tier_and_ rank
0|blitzcra | if entry['queueType'] == 'RANKED_SOLO_5x5':
0|blitzcra | TypeError: string indices must be integers```
!e
""["meow"]
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | /home/main.py:1: SyntaxWarning: str indices must be integers or slices, not str; perhaps you missed a comma?
002 | ""["meow"]
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 1, in <module>
005 | ""["meow"]
006 | ~~^^^^^^^^
007 | TypeError: string indices must be integers, not 'str'
So it runs fine for 50 users, and then it breaks
Is it possible that the error is caused by hitting the rate limit for the Riot API?
sup
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.
# This example requires the 'message_content' intent.
#Imports discord library
import discord.ext
import random
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
#client is the variable of the client function which
# helps the bot make requests to discord for it to function properly
#This also helps us log in with token (links us with the discord bot/token)
client = discord.Client(intents=intents)
#The @ is a decerator (I dont know how it works 100%)
#the async functions help the bot perform multiplt tasks without needing to wait for one to finish
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#the @ symbol indicates a decorator and
#I dont know 100% what they do but they're decerators
@client.event
async def on_message(message):
if message.content.startswith("/hello"):
await message.channel.send("Hello")
print(message.content)
@client.listen
async def help(message):
if message.content.startswith("/help"):
await message.channel.send("What would you like help with?")
print(message.content)```
Damn lol
My token would be at the very bottom but I didnt include it
kk
I documented it thats why its so long
client = discord.Client(intents=intents)
``` you're still using `Client`
it should be bot
that came with the starter code
change discord.Client to commands.Bot
bot = True
the starter code is bad :P
Cannot find reference 'bot' in 'imported module discord'
BRO
what did you change that line to?
client = discord.bot(intents=intents)```
commands.Bot (note capital B as well)
You must also add command_prefix = "$"
what about "?"
Yeah you can add that too
If you want more than one prefix, you can make a list
like
command_prefix = ["$", "?"]
Oh alr
Yep
you can replace these ```py
@client.event
async def on_message(message):
if message.content.startswith("/hello"):
await message.channel.send("Hello")
with bot commands: ```py
@client.command()
async def hello(ctx):
await ctx.send("Hello")
Yeah this way is better
@client.event
async def on_message(message):
if message.content.startswith("?hello"):
await message.channel.send("Hello")
print(message.content)
@client.command()
async def hello(ctx):
await ctx.send("Hello")
print(ctx.content)``` Like this?
yes, you can get rid of the first one now
Alr
Bruh, is it necessary to write that print statement? 
I think it shouldn't be there
Idk it was there before so I just referenced it
does ctx even have a content attribute?
Idk :/
that's wrong
it should probably be ctx.message.content
bro
Dude im new to discord bots
No
this is my 2nd day
this is right

np
But we don't need that too. 'cause we've already added ctx.send("Hello")
Wait whats the question?
we're fixing the starter code they got from somewhere (which uses discord.Client)
Where is the code?
^
Ah? what is exactly help bot is listening on it?
Oh yeahhhh
mhm
the listen doesn't do anything, 'help' isn't a valid event
No reason to import discord.ext btw. And for on_message, use the commands.Bot so you can do prefix commands.
But they told me to add it
who told u?
code golfing
No. Use ```py
from discord.ext import commands
bot = commands.Bot(prefix="!")```
he told me to do import discord.ext and then from discord.ext import commands
Listen, listen on specific event that registered from before ig but i don't think help is a event?
we already did that
no reason to do the import discord.ext if u are going to import from it
Its redundant and pointless
that's for binding more than one function to a single event
I think it should be command_prefix. Right?
Yea its command_prerix
yes sry thats it
if you want normal bot commands, @bot.command() syntax is the correct way
right
Ok let me send the current code
U rlly shouldnt be using the base client, since commands.Bot inherits it.
# This example requires the 'message_content' intent.
#Imports discord library
import discord.ext
import random
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(prefix="?")
#command_prefix = ["$", "?"] for multiple prefixes
#client is the variable of the client function which
# helps the bot make requests to discord for it to function properly
#This also helps us log in with token (links us with the discord bot/token)
client = commands.Bot(intents=intents)
#The @ is a decerator (I dont know how it works 100%)
#the async functions help the bot perform multiplt tasks without needing to wait for one to finish
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
#the @ symbol indicates a decorator and
#I dont know 100% what they do but they're decerators
@client.command()
async def hello(ctx):
await ctx.send("Hello")
But if u are adament about not using predix commands u could technically
command_prefix
Why do u have it twice 
Where
lmao
and again, u dont need the import discord.ext
u have two commands.Bot instantiations
You should remove client variable bruh
Also why you define the bot twice
Why 😕
Where
Anything u can get from discord.ext, u alreayd have when u import from it
bot = commands.Bot(prefix="?")
client = commands.Bot(intents=intents)
Idek what intents is
you don't need the client = commands.Bot() definition anymore, delete it and rename all the decorators to use bot instead of client
Just keep bot = commands.Bot(command_prefix = "?", bot = True, intents = intent)
You have
client which is instance of commands.bot
And you have bot which is instance of commands.bot
Here's no need 2 instances
They're like permissions of the bot
Remove one of them
just do py client = commands.Bot(command_prefix="!", intents=intents)
The data that the bot receives via events from gateway.
Alr I changed it to bot
“bot”
bot > client
!paste
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.
Name doesn't matter
Bruh, I think you should understand it. You shouldn't do whatever we're telling you without even understanding
More understandable
It's literally simple
It's instance actually doesn't matter it can be anything
Bot ,client anything else
It could be camcam
LOL
Yes but 
I agree. Understand what its doing.
Well I got 2 other people telling me something is wrong and im just confused 🤷♂️
Bro this is not discord.Client() instance
LOL
This is commands.bot() instance with name of client
you talking bout bot.commands()?
discord.ext.commands.Bot
bot = commands.Bot(prefix="?")
^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'
@commands.command()
async def rank(self, ctx, member: nextcord.Member, background: Optional[Image.Image] = None):
if background is None:
background = Image.new('RGBA', (500, 170), (0, 0, 0, 0))
a = RankCard(
settings=Settings(),
avatar=member.display_avatar.url,
level=1,
current_exp=1,
max_exp=1,
username="cool username",
background=background
)
image = await a.card3()
await ctx.edit_original_message(file=disnake.File(image, filename="rank.png"))```
``` File "c:\Users\PC\Desktop\Aleccy Bot\cogs\card.py", line 134, in rank
settings=Settings(),
File "c:\Users\PC\Desktop\Aleccy Bot\cogs\card_settings.py", line 57, in __init__
raise InvalidImageType(f"background must be a path or url or a file buffer, not {type(self.background)}")
cogs.error.InvalidImageType: background must be a path or url or a file buffer, not <class 'NoneType'>```
got it
Yea
command_prefix not prefix
# imports
import discord
from discord.ext import commands
# intents indicate what the bot can (and can't) do
intents = discord.Intents.default()
intents.message_content = True
# create the bot
bot = commands.Bot(
intents=intents,
command_prefix='?', # change the prefix here
)
# this will run when the bot connects to discord
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
# this will run when the user runs the command (with '?hello')
# ctx is a context object which contains info about the message that invoked it, the triggering user, etc.
@client.command()
async def hello(ctx):
await ctx.send("Hello")
# run the bot
bot.run("TOKEN HERE")
i tried so many things and still cant fix it
^
I would help, but I dont know the image system.
wdym the image system
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Ur using dpy's Image object right?
AHHHHHHH
from PIL import Image, ImageDraw, ImageFont
Disnake
Oh. Ye idk wat dat is lol
Makes me so mad when I have mistakes on this shit 😡
Doesnt seem like a discord bot problem
seems like a PIL problem
But seemingly ur providing a nontype image
Idek what to fix
What is the error
the rank.png?
Send code again
what's your error now?
!paste
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.
bot = commands.Bot(prefix="?")
^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'
keeps sayin that
I told u already.
Tell me again
commands.Bot(command_prefix = "?")
Bro change prefix= to command_prefix=
bot = commands.Bot(command_prefix="!", intents=intents)```
Why don't they ever read the error
Lol
intents = discord.Intents.default()
intents.message_content = True
Bot.commands(command_prefix = "?")```
^ learning to read traceback is a very useful skill
Good?
Also intents
intents = intents
FUCK
LOL
pls look at my example 😭
It's underlining the fuckin bot thing
Bro dam
^ this is what it should look like
BROOO
WHY IS IT UNDERLINING
What is Bot.commands 😭
FUCKIN HELL BRO THIS SHIT IS SO FRUSTURATING
THEY TOLD ME TO PUT BOT.COMMANDS
😂
who?
just look at my example!!! 😭
YOU FUCKING TOLD ME TO
NO. IT SAYS COMMANDS.BOT 😭
commands.Bot(command_prefix = "?", intents=intents)

Bro learn python
🤣
I did
@bot.command() is for adding commands, you create the bot with commands.Bot
My code is literally the right code 😭
learn discord.py
