#discord-bots

1 messages · Page 210 of 1

zinc jay
#

Uhm

#

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)

naive briar
#

It has to be exactly like what you copied from the portal

#

Without any changes

lost lichen
naive briar
#

Use double quotes instead

lost lichen
#

hmm wait, its something with my env file

#

alright, thanks for the help!

zinc jay
#

await ctx.send(f”The game is now starting! {player_one} vs {player_two}. {current_player}”s turn')

fresh ferry
#

i cant make a url any help ??

naive briar
naive briar
# zinc jay This?

No

await ctx.send(f"The game is now starting! {player_one} vs {player_two}. {current_player}'s turn")
fresh ferry
#

still nothing

naive briar
#

Show all options

fresh ferry
naive briar
#

Did you enable bot in the bot tab

fresh ferry
smoky sinew
#

try refreshing your page

naive briar
#

🤨

smoky sinew
#

@vestal shale don't use a free host, especially not a free discord bot host they're extremely sketchy

vestal shale
#

I made my own bot but I want to host it so it is online 24/7

fresh ferry
#

or a raspberry pi

vestal shale
#

I dont keep it on 24/7 but I have a raspberry pi

smoky sinew
#

you can host it there pretty easily

vestal shale
#

Any recommended yt tuts or something?

fresh ferry
vestal shale
#

I dont care about the bill

smoky sinew
vestal shale
#

As long as its reliable

smoky sinew
#

you can use SCP to transfer code

fresh ferry
#

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

smoky sinew
fresh ferry
smoky sinew
#

scp is already installed

#

and it uses ssh

#

you just have to enable it in the raspberry pi settings

fresh ferry
#
  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('')
torn sail
#

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

shrewd apex
#

out of the box thinking ducky_sphere

fresh ferry
#

use that

smoky sinew
#

literally what's wrong with ssh

smoky sinew
fresh ferry
smoky sinew
#

you can run graphical apps using ssh too

#

it just takes a bit of setup

fresh ferry
smoky sinew
#

the alert channel id

slate swan
#

Yooo @fresh ferry

#

fancy seeing you here lmao

fresh ferry
slate swan
smoky sinew
#

???

#

bruh

torn sail
fresh ferry
#

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'
unkempt canyonBOT
#

: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.

visual yarrow
#

!unmute 977414482903072809

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @fresh ferry.

fresh ferry
#

🥹

slate swan
slate swan
#

Can you show some code?

unkempt canyonBOT
#

: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.

visual yarrow
#

!unmute 977414482903072809

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @fresh ferry.

visual yarrow
fresh ferry
fresh ferry
vocal snow
fresh ferry
slate swan
#

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

slate swan
fresh ferry
golden portal
unkempt canyonBOT
#

: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.

visual yarrow
#

!unmute 741194243930062861

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @slate swan.

fresh ferry
visual yarrow
#

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.

slate swan
#

just know that i create a websocket and on .run_forever i set the ping interval to 41.25 becauses thats what discor dprovided

golden portal
slate swan
golden portal
vale wing
#

You don't decide it

#

Oh wait I misread

#

I am experiencing heavy intelligence level drop

slate swan
#

relatable

slate swan
vale wing
#

Making discord API wrapper in java affected my braincells real hard

#

Even tho I was doing that like a year ago

fresh ferry
#
 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

vale wing
naive briar
#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
fresh ferry
# naive briar Just use discord.py's

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

naive briar
#

Why would you use that

#

It's outdated

slate swan
fresh ferry
fresh ferry
#
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')
naive briar
#

Do not do this

#

And app commands use interactions and not contexts

#

Look in the pins

vale wing
#

If you want the things to be a bit easier use disnake

untold grove
#

anyone know the code for verify command?

vocal snow
#

what is a verify command

untold grove
#

like you need verify before access more chat

shrewd apex
#

looking at your about me i doubt u need it ducky_drawing

naive briar
#

lol

elder smelt
#

hm

vale wing
glad cradle
#

that thing is only for guilds with the COMMUNITY feature enabled

shrewd apex
slate swan
#

Yeah ig

slate swan
# untold grove like you need verify before access more chat

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.

keen iris
#

hi

slate swan
#

Hello

river plank
#

is there anyway to make a command run every 24 hrs?

#

supposing the time doesnt reset even if the bot is restarted

naive briar
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@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").
river plank
#

oo

slate swan
#

Ig it does reset

#

You need to store the time u send then compare the time

river plank
#

oh

#

could ya show a simple example or link me to one?

slate swan
#

Hope it helps

naive briar
slate swan
naive briar
#

What does not execute

timber wren
#

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?

naive briar
#

What does not work about it exactly

bold python
#

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

timber wren
#

my on_member_join event does not work

#

discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

#

this appears on my terminal

naive briar
unkempt canyonBOT
#
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.

bold python
timber wren
# naive briar !traceback
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

bold python
#

i deleted some of the content or else i couldnt send the message

visual yarrow
slate swan
#

anyone knows how i download this

midnight dew
#

!

gilded harness
#

Wait what is client.user in the discord bot code at the start? Is the user the one that interacts with the bot??

gilded harness
#

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

vocal snow
vocal snow
gilded harness
#

Bro is there a website to find all the functions inside of the discord.py library??

#

Like im clueless rn Idk what to do :/

glass dock
naive briar
#

!d discord

unkempt canyonBOT
#

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.

gilded harness
#

like the name is just documents??

gilded harness
glass dock
#

this is documentation

#

Which contain all the functions and their descriptions

gilded harness
glass dock
#

yeap

gilded harness
#

Alr

#

discord.ext.commands???

glass dock
#

Not just

gilded harness
#

Where do I go then

vocal snow
#

Good place to start

glass dock
#

It depends on what you want to find.

glass dock
gilded harness
#

I put my token in it

bold python
#
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

vocal snow
#

You need intents.message_content

bold python
#

so like under the other intents codes that i have $

bold python
bold python
timid pawn
#

Hello guys, i need help with working with tasks on discord bots

naive briar
#

And

timid pawn
#

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

slate swan
#

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.

timid pawn
# slate swan `Loop.stop()` stops the task from looping **after** the current iteration is com...

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

golden portal
timid pawn
white citrus
#
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)```
golden portal
#

!d discord.ext.tasks.Loop.error

unkempt canyonBOT
#

@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.
golden portal
#

use this to capture that error

#

you may wanna use Loop.cancel instead if you wanna cancel it abruptly

timid pawn
timid pawn
slate swan
golden portal
timid pawn
golden portal
#

um oke

timid pawn
# golden portal 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

vale wing
#

!d nextcord.ui.StringSelect

unkempt canyonBOT
#

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.
vale wing
#

@white citrus I believe you need to subclass that ^ instead of Select

#

Although not sure, callbacks implementation in this case is kinda confusing imho

blazing flint
#

can I have help moving my slash commands into their own files

shrewd apex
#

cogs

shrewd apex
vale wing
#

!d nextcord.ui.Select

unkempt canyonBOT
vale wing
#

A it's an alias my bad

sick birch
shrewd apex
#

oh noice

vale wing
#

God knows what

shrewd apex
#

wish there was a inbuilt way to wait for modals to be submitted

vale wing
shrewd apex
vale wing
#

Yeah it is like that

shrewd apex
#

oh well then like that :p

vale wing
#
modal_inter = await modal.wait()```
#

Ya can look at the source it's easy to implement

vale wing
#

Probably would be better to set _fut in init tho

vale wing
shrewd apex
tired pollen
shrewd apex
#

i might want to deal with my current view

slate swan
#

Ohh

vale wing
#

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

sick birch
#

Bobux bot

Bobux bot

shrewd apex
#

aniblobsweat cliff hanger

shrewd apex
#

@vale wing

cloud dawn
#

Bobbot

#

🫠

slate swan
quick gust
#

It's an economy bot

sick birch
#

infinite Bobux

slate swan
glad cradle
hushed galleon
#

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

vale wing
shrewd apex
#

apparently didnt find the key while popping

vale wing
#

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

shrewd apex
#

ic

vale wing
#

@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

shrewd apex
#

oh right i do respond

#

inter.send

vale wing
#

That's one of disnake's main advantages over dpy with interaction.response.send_message

shrewd apex
#

tru

#

i like disnakes interactions implementation

vale wing
vale wing
fair shuttle
#

it might be stupid but why it says undefined name 'member and ctx?

#

only on this line

vale wing
#

It is outside of function

#

Set it to 4 spaces, indents are fr barely visible

unkempt canyonBOT
#
Indentation

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

bold python
#

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

slate swan
bold python
#

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.

bold python
#

Realy?

slate swan
vale wing
#

Except it was once moved from on_member_update to on_voice_state_update or smth, I don't remember exact event name

bold python
#

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

vale wing
#

!d discord.on_voice_state_update surprisingly I remember it correctly

unkempt canyonBOT
#

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...
bold python
#

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 ?

slate swan
#

spotify has similar issues

#

you can use soundcloud upto some extent tho

vale wing
#

Does spotify have API that allows you to stream audio? I suspect it does not

bold python
#

I dont know

vale wing
#

Soundcloud had some issues with getting API key when I last tried

#

You had to like send them a google form which was closed 🗿

bold python
#

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.

vale wing
#

Actually what for would you need youtube bot? Discord's got youtube activity now

bold python
#

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.

bold python
#

@bot.event
async def on_voice_state_update(member, before, after):
# my code here?

vale wing
#

Similar

bold python
#
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()
vale wing
#

If you help us make a site for it sure 😃

bold python
vale wing
#

What

bold python
#

my yt bot highly illigal but infinite robux

vale wing
#

Infinite bobux is legit

bold python
#

bobux?

vale wing
#

Meme crypto

bold python
#

ah i tought yall ment robux from roblux or some

#

nvm i go check the code see if it works

slate swan
#
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'
bold python
# slate swan ```py class carwsd(commands.Cog): def __init__(self, bot): self.bot ...

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.

bold python
# slate swan 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

slate swan
#

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'```
bold python
#

ok 1 sec

bold python
#

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.

slate swan
#
  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'```
cinder tulip
#
@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?

slate swan
#

im very sorry for asking all these qquestions

bold python
#

NoaA i send you a private dm real quick i show u smt

cinder tulip
slate swan
#

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

cinder tulip
#

I tried removing it but i got this instead

slate swan
#

show updated code

cinder tulip
#
@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)
slate swan
#

it's interaction.user

#

you might have got an attributerror

cinder tulip
#

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!

slate swan
#

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

bold python
#

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

slate swan
#

it needs a function after @bot.event decorator

#

so it gives error since there is no function bellow

fair shuttle
#

how i can fix that i never got this bfore

bold python
#

just copy paste

fair shuttle
#

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

bold python
#

try this ```fut = asyncio.ensure_future(arg, loop=loop)

fair shuttle
#

yeah

fair shuttle
#

also i tried to do a level system and everytime sm1 send a message this error appear

bold python
#

and btw did the last one hekpo the lsat code?

fair shuttle
#

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

blazing flint
#

can someone help me move my discord.py slash commands into their own respective files

blazing flint
blazing flint
#

I am using slash commadns

naive umbra
#

yeah, that's not a problem

blazing flint
#

can you help me through

naive umbra
blazing flint
#

I have done similar stuff with javascript before

#

ok

#

can I ask you if I have any questions

naive umbra
#

just ask here, if im not able to help then someone else will most likely help you

blazing flint
#

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

tired pollen
blazing flint
#

Ik

#

JS is simple in terms of discord bots

blazing flint
#
@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")
tired pollen
#

Yea but don't use it on on_ready event

blazing flint
#

yeah

#

my command does not register with this

tired pollen
#

Use setup_hook event instead

naive umbra
#

slash commands needs to be synced

blazing flint
#

yeah I am

naive umbra
#

where?

blazing flint
#

my bot was working before

#

I am trying to sync them after moving them now

#

that is what I want help with

tired pollen
#

Also I don't think client support cog

blazing flint
#

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 :)")

tired pollen
#

Ig you need to use bot instead of client

blazing flint
#

I call it client

tired pollen
#

Oh right

blazing flint
#

but I use the Bot subclass

#
client = commands.Bot(command_prefix = "!", intents=intents)```
slate swan
#

are you trying to create slash commands in cogs?

blazing flint
#

yes

fair shuttle
slate swan
blazing flint
#

kinda

tired pollen
#

You should use
@app_commands.command() decorator in cogs if i remember correctly(for slash commands)

blazing flint
#

ok

slate swan
# blazing flint kinda

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

blazing flint
#

so does load_extension() sync it?

tired pollen
#

No

naive umbra
#

no, you need to call sync on the tree manually

#

preferably, in a prefix command

tired pollen
#

load_extension just load the cogs you need to sync it manually

blazing flint
#

dang I accidentally removed the sync part of my on_ready event

slate swan
blazing flint
#

what is the function to sync commands again

slate swan
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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.
blazing flint
#

do I do like client.tree.sync

slate swan
#

yes

#

you need to call and await it too

blazing flint
#

perfect

#

lol the command I moved to it's own file still does not load

#

@slate swan

slate swan
#

how did you create it, show code

blazing flint
#

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")```
naive briar
#

And you need to await the coroutine

blazing flint
#

cog

#

yeah Ik

#

thanks for reminding me tho

slate swan
#

!d discord.app_commands.CommandTree.add_command (test)

unkempt canyonBOT
#

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.
slate swan
#

yeah so just create a setup function in the extension file, and use bot.tree.add_command there

blazing flint
#

I dont lol

slate swan
#

that won't be a cog but you will be able to seperate your commands into diff file

naive umbra
# blazing flint I dont lol
    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

blazing flint
#

the sync is outside of the l

#

of wait its not

tired pollen
#

Also add function called setup at end of you code then add cogs like example

blazing flint
#

I am so confused

naive briar
#

Extensions and cogs are different

blazing flint
#

I just want to be able to put my slash commands into their own respective files

tired pollen
tired pollen
blazing flint
#

Well I have the first part done

#

of loading the comands with load_extension

tired pollen
#

Also if you just want to create 1 command per file then just use extension

blazing flint
#

that is exactly what I want to do

blazing flint
#

but how do I register the extension

fair shuttle
#

i got this error when sm1 type a message in the server for the leveling system

blazing flint
#

I already have done what that article says

tired pollen
blazing flint
#

yeah

tired pollen
#

You need to do it manually

#

tree.sync()

tired pollen
blazing flint
#

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

#

?

tired pollen
#

Hmm idk about that but don't do anything in on_ready use setup_hook event instead

blazing flint
#

so replace on_ready with setup_hook

#

what is setup_hook exactly?

tired pollen
#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

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")...
blazing flint
#

when I replace on ready with it my bot just stops

tired pollen
#

what?

#

can you give the code

blazing flint
#
@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")```
tired pollen
#

i have no idea

blazing flint
#

Dam

tired pollen
#

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

blazing flint
#

it works now

blazing flint
#

I just still have not been able to sync

#

@tired pollen it runs now I dont know why it did not that one time

pulsar bridge
#

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?

blazing flint
#

Mm

#

I don’t think it has anything to do with a vpn

#

Does the bot dm you first?

#

@pulsar bridge

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 🤔

blazing flint
#

Oh

#

That’s interesting

blazing flint
#

Also try sending code formatted messages instead of screenshots

#

And include the section of code causing the error for future reference

smoky sinew
blazing flint
#

Do I just run sync whenever I add a new command

#

And where do I run it @smoky sinew

smoky sinew
blazing flint
#

Ok

#

Can I just do it in on_ready

#

I have my bot in three servers

smoky sinew
#

why

#

that's not any better

blazing flint
#

There is no disadvantage

torn sail
#

on_ready can be called multiple times during the bots running

golden portal
#

you would also get ratelimit due to the syncing, especially global sync ones, that is a disadvantage

young dagger
#

Why do some people still use requests instead of aiohttp?

#

What are the advantages of using requests?

golden portal
#

thats just it tbh, its a sync library, aiohttp is the asyncio alternative

slate swan
#

You should be using aiohttp if you're working with a Discord bot

vocal snow
smoky sinew
#

because sometimes cogs aren't loaded by then

vocal snow
#

The load_extension calls are happening before the sync

smoky sinew
#

yes

#

and if you restart your bot often you're going to get ratelimited without changing any commands

gusty flax
#

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

keen cloak
#

hello>

#

help anyone?

gusty flax
keen cloak
#

My discord bot ( kick command

#

Will u help?

gusty flax
sick birch
keen cloak
vale wing
#

Iirc you can send 1000 Identify calls once per day or something

vale wing
gusty flax
#

Why wat

sick birch
#

Ignore. Was trying to make a bad joke, lol

gusty flax
#

sad trombone plays

maiden fable
#

I feel ya Robin

light violet
#

how are they able to implement slash cmd in a webhook?

naive briar
#

Not possible

vale wing
light violet
vale wing
dull terrace
vale wing
#

You can't respond to an interaction with webhook

#

Just look at API docs

glad cradle
#

Well at least not with the type of webhooks that we know of

light violet
#

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

dull terrace
light violet
glad cradle
#

I'm not sure but maybe it has something to do with followup

glad cradle
vale wing
# light violet its a webhook bro

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

tired pollen
fresh fern
#

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

vale wing
#

@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

naive briar
fresh fern
#

its fixed no worries

naive briar
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

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.
fresh fern
#

thanks btw

rocky geyser
#

!code

unkempt canyonBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

rocky geyser
#

!codehelp

#

!d discord hyperlinks in embed

#

Bruh

slate swan
shrewd fjord
#

!d time.sleep

unkempt canyonBOT
#

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.
shrewd fjord
#

Working lol

shadow vigil
#

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 💀ducky_sphere

#

idk how that happend it was in tests folder

slate swan
#

Nice

#

how to do like if there is discord.ext.commands.errors.MemberNotFound: then dont throw error instead send message in a channel

slate swan
slate swan
#

it throws error i dont want that

shadow vigil
fresh fern
#

on_commmand_error

#
  if isinstance(error, errorName):
    what to do```
#

how to purge messages in a cog

cloud dawn
#

!d discord.discord.ext.commands.on_command_error

unkempt canyonBOT
#

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")).
fresh fern
#

slash command

#

no need raise error

#

help ME anyone

shadow vigil
#
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

cloud dawn
# cloud dawn !d discord.discord.ext.commands.on_command_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)
fresh fern
shadow vigil
fresh fern
#

no one?

fresh fern
shadow vigil
fresh fern
#

ok ok

tired pollen
fresh fern
#
    @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

slate swan
#

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

fresh fern
#

it says the application did not respond

slate swan
#
@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???

fresh fern
#

NOOOOOO

shadow vigil
fresh fern
#
@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

cloud dawn
fresh fern
#

help me

shadow vigil
# fresh fern na

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

cloud dawn
fresh fern
fresh fern
#

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)```
cloud dawn
tired pollen
#

Do you have error handler eating you errors?

tired pollen
#

Yes

shadow vigil
slate swan
fresh fern
#

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)```
slate swan
#

rows have been deprecated for a long time

any new way?

#

it worked but it throws error in terminal

fresh fern
shadow vigil
fresh fern
cloud dawn
#

You basically have this View called Confirm and that gets passed inside a send() function.

fresh fern
slate swan
shadow vigil
tired pollen
cloud dawn
fresh fern
shadow vigil
fresh fern
shadow vigil
fresh fern
#

it said this "The application did not respond"

tired pollen
cloud dawn
#

Now that I think about it you can overengineer the crap out of the purge it can do so much.

cloud dawn
tired pollen
shadow vigil
fresh fern
tired pollen
#

Put an else after your if statement and raise any other error@fresh fern so your error handler don't eat errors

shadow vigil
tired pollen
#

raise error

fresh fern
#

ok ok

tired pollen
#

Or whatever you called error

fresh fern
#

what does that mean

#

i also want to learn not just copy paste

tired pollen
#

You passed error as arg right?

shadow vigil
fresh fern
#

yea yea

tired pollen
#

It can be anything

fresh fern
#

still it said that'

shadow vigil
#

!e

raise TypeError("just an example")
unkempt canyonBOT
#

@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
fresh fern
#

the bot said "The application did not respond"

#

but purged the msges

naive briar
#

You didn't respond then

fresh fern
#

what should i respond in purge

tired pollen
#

response

cloud dawn
#

Cleared X amount of message or smth.

fresh fern
#

ok i thought that purge should be secret

cloud dawn
#

Ephemeral.

tired pollen
#

Actually you need to response to an interaction or will give you application does not response or something like that

fresh fern
tired pollen
#

That's will not raise error but on discord it says that

cloud dawn
#

I do recommend making it defer since sometimes it can take a bit longer than 3 seconds.

tired pollen
#

Response to an interaction by defering it or
!d discord.InteractionResponse.send_message

cloud dawn
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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...
fresh fern
#

whats defer

tired pollen
#

Yea that

tired pollen
slate swan
#

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)```
tired pollen
cloud dawn
# fresh fern whats defer

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.

fresh fern
cloud dawn
tired pollen
fresh fern
#

my laptop was 100% 30min ago now 27%??

#

whats up with this thing man

cloud dawn
tired pollen
#

ik that don't send message but you will have access to original res

cloud dawn
#

Yep.

shadow vigil
slate swan
#

could anyone help me?

#

hey my code is working but an error is thrown in terminal
shall i use try - expect? will that work?

slate swan
#

yes

cloud dawn
slate swan
tired pollen
slate swan
# tired pollen 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
        
tired pollen
#

Bro remove raise error

cloud dawn
tired pollen
#

That's actually means if error is an instance of memberNotFound class return true otherwise return false

cloud dawn
#

Also idk how much discord.py likes it if you overwrite a function with this one.

tired pollen
#

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?

fresh fern
#

help again 😅

#

anyone??

naive briar
#

Just ask your questions

slate swan
tired pollen
#

If error is not member not found then it will raise the error

shrewd fjord
#

Just do,
return await ctx.send(..)
so you dont need else statement

slate swan
tired pollen
tired pollen
#

The error is member not found?

shrewd fjord
#

Can you try this?

shrewd fjord
tired pollen
#

i try both method

shrewd fjord
tired pollen
#

Yea

slate swan
#

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```
tired pollen
#

Bro wth

#

That's why you are getting error

#

also do you know what elif is?

naive briar
#

Or just basic Python in general

shrewd fjord
#

2 command error event? 💀

tired pollen
#

Well , that will work but ig elif is better way?

shrewd fjord
#

iirc you can have only one same event with .event and can have multiple same event with .listen()

shrewd fjord
tired pollen
#

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

naive briar
#

Linda

#

Wait no, dumb autocorrect

#

Kinda

shrewd apex
slate swan
gusty flax
tired pollen
slate swan
#

there is event that is called on any command error

young dagger
#
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

slate swan
unkempt canyonBOT
#

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.
young dagger
# slate swan 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}"```
slate swan
#

try to change print(entry) to print(entry.encode("utf-8"))

naive briar
slate swan
#

error message says its at print huh

naive briar
#

Oh yeah, I'm probably going blind

young dagger
slate swan
#

hm right cause this is dict

naive briar
#

I never think printing should be where errors will ever come from

slate swan
#

right

#

can you print data ? or same error

young dagger
#

And I think it's okay forn ow

slate swan
#

okay then

young dagger
#

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```
naive briar
#

!e

""["meow"]
unkempt canyonBOT
#

@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'
young dagger
#

So it runs fine for 50 users, and then it breaks

young dagger
gilded harness
#

sup

austere prairie
#

send the code here

#

!paste

unkempt canyonBOT
#
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.

gilded harness
#
# 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)```
echo mural
#

Damn lol

gilded harness
#

My token would be at the very bottom but I didnt include it

echo mural
#

kk

gilded harness
austere prairie
#
client = discord.Client(intents=intents)
``` you're still using `Client`
echo mural
#

it should be bot

gilded harness
#

that came with the starter code

austere prairie
#

change discord.Client to commands.Bot

echo mural
#

bot = True

austere prairie
gilded harness
#

Cannot find reference 'bot' in 'imported module discord'

echo mural
#

BRO

austere prairie
#

what did you change that line to?

gilded harness
#
client = discord.bot(intents=intents)```
austere prairie
#

commands.Bot (note capital B as well)

gilded harness
#

Oh

#

Alr its good now

echo mural
#

You must also add command_prefix = "$"

gilded harness
#

what about "?"

echo mural
#

Yeah you can add that too

#

If you want more than one prefix, you can make a list

#

like
command_prefix = ["$", "?"]

gilded harness
#

Oh alr

echo mural
#

Yep

austere prairie
#

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")
gilded harness
#

@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?
austere prairie
#

yes, you can get rid of the first one now

gilded harness
#

Alr

echo mural
#

I think it shouldn't be there

gilded harness
#

Idk it was there before so I just referenced it

austere prairie
#

does ctx even have a content attribute?

gilded harness
#

Idk :/

echo mural
#

that's wrong

austere prairie
#

it should probably be ctx.message.content

echo mural
#

bro

gilded harness
#

Dude im new to discord bots

gilded harness
#

this is my 2nd day

echo mural
gusty flax
echo mural
echo mural
gusty flax
#

Wait whats the question?

austere prairie
#

we're fixing the starter code they got from somewhere (which uses discord.Client)

gusty flax
#

Where is the code?

tired pollen
#

Ah? what is exactly help bot is listening on it?

echo mural
#

mhm

austere prairie
gusty flax
gilded harness
#

But they told me to add it

echo mural
gilded harness
#

code golfing

gusty flax
gilded harness
#

he told me to do import discord.ext and then from discord.ext import commands

tired pollen
gusty flax
#

Its redundant and pointless

austere prairie
echo mural
tired pollen
gusty flax
austere prairie
#

if you want normal bot commands, @bot.command() syntax is the correct way

echo mural
#

right

gilded harness
#

Ok let me send the current code

gusty flax
#

U rlly shouldnt be using the base client, since commands.Bot inherits it.

gilded harness
#
# 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")
gusty flax
#

But if u are adament about not using predix commands u could technically

gilded harness
#

Where

echo mural
#

lmao

gusty flax
#

and again, u dont need the import discord.ext

gusty flax
echo mural
#

You should remove client variable bruh

tired pollen
#

Also why you define the bot twice

gilded harness
#

Why 😕

gilded harness
gusty flax
#

bot = commands.Bot(prefix="?")
client = commands.Bot(intents=intents)

gilded harness
#

Idek what intents is

austere prairie
echo mural
#

Just keep bot = commands.Bot(command_prefix = "?", bot = True, intents = intent)

tired pollen
# gilded harness Where

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

echo mural
tired pollen
#

Remove one of them

gusty flax
#

just do py client = commands.Bot(command_prefix="!", intents=intents)

gusty flax
gilded harness
#

Alr I changed it to bot

fresh ferry
#

!paste

unkempt canyonBOT
#
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.

tired pollen
gusty flax
#

personal preference ig

echo mural
slate swan
#

More understandable

echo mural
#

It's literally simple

tired pollen
#

Bot ,client anything else

echo mural
#

It could be camcam

echo mural
#

LOL

slate swan
gusty flax
gilded harness
tired pollen
tired pollen
#

This is commands.bot() instance with name of client

echo mural
tired pollen
echo mural
#

ohhhhh

gilded harness
#

bot = commands.Bot(prefix="?")
^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'

slate swan
#
    @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'>```
echo mural
#

got it

tired pollen
#

Yea

austere prairie
#
# 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")
slate swan
gusty flax
slate swan
naive briar
#

!traceback

unkempt canyonBOT
#
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.

gusty flax
gilded harness
#

AHHHHHHH

slate swan
tired pollen
gusty flax
gilded harness
#

Makes me so mad when I have mistakes on this shit 😡

gusty flax
#

Doesnt seem like a discord bot problem

gusty flax
#

seems like a PIL problem

slate swan
#

9.4.0

gusty flax
#

But seemingly ur providing a nontype image

gilded harness
#

Idek what to fix

gusty flax
slate swan
#

the rank.png?

tired pollen
echo mural
slate swan
#

!paste

unkempt canyonBOT
#
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.

gilded harness
#

bot = commands.Bot(prefix="?")
^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'

#

keeps sayin that

gilded harness
#

Tell me again

echo mural
tired pollen
gusty flax
#
bot = commands.Bot(command_prefix="!", intents=intents)```
naive briar
#

Why don't they ever read the error

slate swan
tired pollen
gilded harness
#
intents = discord.Intents.default()
intents.message_content = True
Bot.commands(command_prefix = "?")```
austere prairie
gilded harness
#

Good?

gilded harness
#

FUCK

echo mural
#

LOL

gilded harness
#

It's underlining the fuckin bot thing

tired pollen
#

Bro dam

austere prairie
echo mural
gilded harness
#

WHY IS IT UNDERLINING

gilded harness
#

FUCKIN HELL BRO THIS SHIT IS SO FRUSTURATING

gusty flax
#

its commands.Bot

#

😭

gilded harness
#

THEY TOLD ME TO PUT BOT.COMMANDS

echo mural
#

😂

gusty flax
gusty flax
gilded harness
gusty flax
echo mural
gusty flax
tired pollen
echo mural
gilded harness
austere prairie
gusty flax
#

My code is literally the right code 😭

echo mural