#discord-bots

1 messages · Page 1096 of 1

sick birch
#

It may be causing a name conflict

slate swan
#

I removed the import, only what to insert instead of it?

regal pulsar
#

self.client

slate swan
# regal pulsar self.client

🥺

    @commands.Cog.listener()
    async def on_member_join(self, member: discord.Member):
        channel = self.client.get_channel( 977252614498582538)

        role = discord.utils.get ( member.guild.roles, id = 977252174964871258)

        await member.add_roles (role)
        await channel.send ( embed = discord.Embed (description = f"``{member.name}``, добро пожаловать на сервер", color = 0xffffff))
sick birch
#

Did you bind the commands.Bot instance to your class?

regal pulsar
#
def __init__(self, client: discord.Client):
    self.client = client
sick birch
#

But use commands.Bot instead

regal pulsar
#

Yeah

slate swan
#
    @commands.Cog.listener()
    async def __init__(self, member, client: discord.Client):
        self.client = client
        channel = self.client.get_channel( 977252614498582538)

        role = discord.utils.get ( member.guild.roles, id = 977252174964871258)

        await member.add_roles (role)
        await channel.send ( embed = discord.Embed (description = f"``{member.name}``, добро пожаловать на сервер", color = 0xffffff))

😖

sick birch
#

In your setup function you need to instantiate it with the commands.Bot instance

#
def setup(bot: commands.Bot):
  bot.add_cog(mod(..., bot))

If 2.0, use the async version

slate swan
#

Works, Works!!! You are so great at explaining everything. It's not the first time I've been here. Thanks

slate swan
#

yes :troll:

rocky hornet
#

show TrollSmile

stable leaf
#

i recently switched to nextcord and i don't know how to send direct messages to only one user, in discord.py it was like this ```py
member = bot.get_user(The ID of user)
await member.send("Message")

rocky hornet
#

try asking nextcord users

#

@stable leaf

stable leaf
#

is here a nextcord channel?

fading marlin
stable leaf
fading marlin
#

get_user isn't finding the user that you've specified so it's returning None. You probably have some messed up intents or try using fetch_user

odd mango
#
@client.event
async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
    if getattr(ctx, 'handled', False):
        return

    if isinstance(error, commands.TooManyArguments):
        await ctx.send('Too many arguments.')
    elif isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f'Missing required argument `{error.param.name}`.')
    elif (isinstance(error, commands.NotOwner) or isinstance(error, commands.MissingPermissions)):
        await ctx.send('You do not have the required permissions to invoke this command.')
    elif (isinstance(error, commands.CommandOnCooldown) or isinstance(error, commands.CheckFailure)):
        await ctx.send(error)
    elif isinstance(error, commands.BadArgument):
        await ctx.send(f'Bad argument: {error}')
    elif isinstance(error, commands.BotMissingPermissions):
        await ctx.send('Oops! The bot does not have the required permissions to execute this command.')
        log.error(f'{ctx.command.qualified_name} cannot be executed because the bot is missing the following permissions: {", ".join(error.list)}')
    elif isinstance(error, commands.CommandInvokeError):
        await ctx.send('Something went wrong internally!')
        log.error(f'{ctx.command.qualified_name} failed to execute. {error.original.__class__.__name__}: {error.original}\n{"".join(traceback.format_tb(error.original.__traceback__))}')```
does this look fine? or do i need to handle any more errors?
#

oh and also do i need to put

return error``` after each if/elif?
odd mango
#

great

fading marlin
slate swan
velvet compass
odd mango
fading marlin
#

well you don't seem to have a get_bank_data function

slate swan
velvet compass
fading marlin
slate swan
fading marlin
#

get_bank_data isn't defined in the line of your code

velvet compass
slate swan
#

ii have a check for this

                            def check(msg):
                                return msg.author == ctx.author and msg.channel == ctx.author.dm_channel
velvet compass
fading marlin
#

but why
well cause otherwise python has no clue what get_bank_data even does
how do i define it
this is basic python, please learn some of the basic stuff before trying out more complicated stuff like anything discord-library-related

slate swan
#

i accidentally left it out

velvet compass
#

Hmm. I'm not too sure to be honest

keen mural
#

Any1 know where i can learn slash commands

odd mango
fading marlin
#

yes

odd mango
#

cool, thanks a bunch

fading marlin
odd mango
#

lee quick question, can i make my bot send any red text which comes in console to a certain discord channel in form of a file? cause errors can be VERY long

#

i think its called stderr?

slate swan
#

i have a feeling because of the while and something messes it up

fading marlin
odd mango
#

oh okay so the error then, can i make my bot send it in a channel?

fading marlin
odd mango
#

how do i try catch all errors though

slate swan
odd mango
#

is there any common handling function?

fading marlin
fading marlin
odd mango
# fading marlin wdym?

like all the red text in the console, gets dumped to a discord channel, regardless of its being a TypeError or CommandNotFound or BadArguements are whatsoever

#

just whatever is red

slate swan
#

its so weird because it works now, but when i do it again it doesnt work anymore

fading marlin
fading marlin
slate swan
#

oh no its from python

fading marlin
#

wait_for doesn't raise TimeoutError, it raises asyncio.TimeoutError

slate swan
#

oh okay thank you

slate swan
fading marlin
#

why?

slate swan
#

why not?

fading marlin
#

just get the channel and send it there? no need to use http methods?

slate swan
odd mango
#

i mean i am not gonna delete the logging channel ever

#

so i doubt i will be getting None

fading marlin
#

it's 1 less API call ._. huh, well I mean they could just DM the error 🤷

slate swan
#

why even get the object...using http methods is lesser work

fading marlin
maiden fable
#

Would love it if Danny or a contrib comes here and sees people suggesting others to use http methods

slate swan
#

he already got mad at me once for doing that in the dpy server

fading marlin
#

lmao

maiden fable
#

dpy server- his territory
python server- not his territory

tacit horizon
#

how can i input more then one word
like !say lksdfjl;askjf;laskjdf;laskjdf;laskjdf;laskjfd

slate swan
#

I mean, common sense says

channel = bot.get_channel(id) or await bot.fetch_channel(id)
await channel.send(...)

''' or '''

from discord import http
await bot.http.send_message(channel_id, http.handle_message_parameters(content="uwu"))
odd mango
#

inoknowshttp

tacit horizon
#

ok

fading marlin
#

those are some nice function names

maiden fable
#

Thanks for deleting that Savvy

odd mango
slate swan
odd mango
slate swan
#

and the timeouterror still doesnt trigger

except asyncio.TimeoutError:
                                                await ctx.author.send("Your Captcha expired. You will be kicked.")
slate swan
odd mango
#

i dont want specific ones

#

i want all the red text in console

slate swan
#

async def on_command_error(ctx, error): http_method(content=error)

odd mango
#

look

fading marlin
odd mango
#

i am saying not just the command errors, but ALL errors

slate swan
#

!d discord.on_error

unkempt canyonBOT
#

discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.10)").

If you want exception to propagate out of the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") class you can define an `on_error` handler consisting of a single empty [raise statement](https://docs.python.org/3/reference/simple_stmts.html#raise "(in Python v3.10)"). Exceptions raised by `on_error` will not be handled in any way by [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
odd mango
#

this is still a discord error event

slate swan
#

I want make a command that allowed me to set the channel where the bot would send messages. For example: .defineSuggestions #channel (it would define a specific channel for the suggestions) and then .sendSuggest (suggestion) and it would send the suggestion in that channel. Any suggest?

odd mango
#

i am saying ALLLLLL

#

NoneType and stuff, and stuff and sruff

slate swan
#

is mongodb down?

odd mango
#

or maybe rate limits

#

or a website blocking the program

#

or failed to fetch some data

#

all the damned possible errors

slate swan
odd mango
#

i just gave it for an example 😭

#

like not just discord related errors

#

but all

slate swan
#

well, idk, do you have some other functions that could return None?

#

which arent commands probably

#

and do you call those functions within commands

#

and I think on_command_error makes it possible to pretty much handle every error

odd mango
#

maybe fetch json data

slate swan
odd mango
#

yeah its on initialization

fading marlin
#

on_error covers all exceptions though? even those raised outside of commands?

slate swan
#

I just said that....

#

and was gonna say it again but nvm

odd mango
#

ohh peace then

slate swan
#

I hate trying to help in this channel anymore now

fading marlin
#

do or do not, there is no try yoda

quaint epoch
#

🔫

fading marlin
#

maybe

slate swan
#

@bot.command() async def add(ctx): if ctx.author.id not in dev: await ctx.send("Contact staff to buy premium") else: if ctx.author.id not in premium: premium.append(ctx.author.id) await ctx.send("Premium **SUCCESSFULLY** enabled")

#

any who can help

odd mango
full lily
slate swan
#

idk why but its dont add user id

full lily
slate swan
full lily
#

why not

slate swan
#

because code didnt append user id to list

full lily
#

are you getting an error?

slate swan
#

no

full lily
odd mango
# fading marlin sure

how do i send the error instead of go open the file and check error wazacxauhz ? that would be a lot cooler

slate swan
full lily
slate swan
fading marlin
odd mango
#

yeah! thanks

full lily
#

add a debug print statement under this line so we see if it's true or not

slate swan
#

but its didnt work

full lily
#

are you sure it's true?

#

Are you sure it's not being appended?

#

print the list after that line. Is it still empty?

slate swan
maiden fable
odd mango
#

but nothing in the discord channel

heady sluice
#

you might have another error handler which handles this error before on_error

odd mango
#

nope

heady sluice
#

also, why are you taking *args, **kwargs? Confused_Dog

odd mango
#

no idea just thought i should take

heady sluice
#

would you mind sharing your whole code? you don't have to paste every command

#

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

fading marlin
heady sluice
#

tasks

#

loading cogs

odd mango
heady sluice
#

you just said you have on_error

odd mango
#

besides that DUH

heady sluice
heady sluice
#

what about changing on_error to on_command_error

#

and taking only ctx and error

odd mango
#

no no no no i need all errors not just command errors

heady sluice
#

sure just for tests

odd mango
#

okay

fading marlin
heady sluice
#

tasks and loading cogs

#

😭

odd mango
fading marlin
slate swan
#

!d discord.on_error

unkempt canyonBOT
#

discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored. If you want to change this behaviour and handle the exception for whatever reason yourself, this event can be overridden. Which, when done, will suppress the default action of printing the traceback.

The information of the exception raised and the exception itself can be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.10)").

If you want exception to propagate out of the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") class you can define an `on_error` handler consisting of a single empty [raise statement](https://docs.python.org/3/reference/simple_stmts.html#raise "(in Python v3.10)"). Exceptions raised by `on_error` will not be handled in any way by [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
odd mango
#

@heady sluice yeah so it works w on_command_error so is the test done?

#

what to do for on_error

heady sluice
#

yes

#

seems like on_error doesn't handle command exceptions

#

or just this specific one

#

dunno

odd mango
#

also

#

this is not quite

warm torrent
#

thanks it works !

slate swan
#

you can only dm the visible members anyways...

slate swan
keen mural
#

how do i send a message to a specific channel again

pure crypt
#

on message event or command?

keen mural
#

on member join

tough lance
pure crypt
#

first get the channel and safe it in a variable. Like: channel = bot.get_channel(id). Then await channel.send(‘message’)

keen mural
#

ok thanks

pure crypt
#

try the first befause i’m not that god

tough lance
#

I'm not that good also crazyeyes

keen mural
#

no error messages

tough lance
#

Do you have intents enabled?

odd mango
#

how do i trigger TooManyArguments?

fading marlin
#

raise commands.TooManyArguments(...)

odd mango
#

no not like that

#

like manually using a command

keen mural
odd mango
#

i tried putting an extra arg in the command but that didnt work

fading marlin
#

wdym?

mental kindle
#
10.06 20:28:33 [Bot] File "/main.py", line 6, in <module>
10.06 20:28:33 [Bot] import discord
10.06 20:28:33 [Bot] ModuleNotFoundError: No module named 'discord'

how do I fix this? I'm going through pebblehost and I've got everything in requirements

odd mango
#

i did pokestat xyz xyz xyz

#

so that should trigger it right? does nothing

#

it triggers command invoke error for some reason

fading marlin
#

uh

odd mango
#

i mean, when i do pokestat xyz xyz xyz, it just considers pokestat xyz and ignore the latter text

#

so idk how to trigger too many arguments

fading marlin
mental kindle
#
ImportError: cannot import name 'app_commands' from 'discord' (/.local/lib/python3.9/site-packages/discord/__init__.py)
tough lance
mental kindle
#

yeah I've got that installed, It's interesting cuz I have the bot working on a different machine but wasn't actually being hosted. I'm going through pebblehost atm and I've got everything in their requirements

#
10.06 21:02:52 [PebbleHost Loader] Installing discord.py
tough lance
#

python -m pip install -U git+https://github.com/Rapptz/discord.py

mental kindle
#

well through the site but that's the one I'm assuming is the correct one

#
discord
discord.py 
asyncpg
asyncio
json
requests
http
numpy 
tweepy
base64
random

don't think all that is necessary but I just added everything into their requirements.txt so really unsure what I'm missing/doing wrong

torn sail
#

It should be member.edit not member.username

slate swan
#

guys can anyone help me attach ffmpeg-static to PATH

pure crypt
#

how can i made it that i have to ping inuser in a command?

slate swan
rocky trench
slate swan
#

no windows

rocky trench
#

Install ffmpeg.exe and get the path lol

slate swan
#

how exactly lol

rocky trench
#

Uh, go to the site to download, then copy the path, then define the location inside the file

slate swan
#

what do i copy

rocky trench
#

The path

slate swan
#

no i mean getting ffmpeg inside path

#

i do not want to change the path location

rocky trench
#

I don't think you need it in the path

slate swan
#

i do

rocky trench
#

However I am sure there is plenty of information on YouTube and internet

#

I'm not good at adding stuff to PATH, it's disgusting

slate swan
rocky trench
vale wing
#

Why add to PATH when you can just parse the executable path to executable param 🤨

vale wing
#

!d discord.FFmpegPCMAudio

unkempt canyonBOT
#

class discord.FFmpegPCMAudio(source, *, executable='ffmpeg', pipe=False, stderr=None, before_options=None, options=None)```
An audio source from FFmpeg (or AVConv).

This launches a sub-process to a specific input file given.

Warning

You must have the ffmpeg or avconv executable in your path environment variable in order for this to work.
vale wing
#

See the executable

#

Just parse the path to downloaded ffmpeg

slate swan
#

bruh i'm a beginner i do not understand any of this shit

vale wing
#

And you just copypaste code?

slate swan
#

no

vale wing
#

Good

slate swan
#

learn things here and there

#

and then choose the perfect code

#

use it and solve some errors

vale wing
#

Just download the ffmpeg executable, put it into your project folder and set the executable param of your audio source constructor to ./ffmpeg.exe

vale wing
slate swan
#

i mean the perfect line of code

vale wing
#

Ok got it, right method

slate swan
#

i've dealing with this for a day and a half

slate swan
#

i also need help making a loop code

#

here is main.py ```import discord
from discord.ext import commands
import music

cogs = [music]

client = commands.Bot(command_prefix='?', intents = discord.Intents.all())

for i in range(len(cogs)):
cogs[i].setup(client)

client.run('token')```

#

here is music.py ```import discord
from discord.ext import commands
import youtube_dl

class music(commands.Cog):
def init(self, client):
self.client = client

@commands.command()
async def join(self,ctx):
    if ctx.author.voice is None:
        await ctx.send("You're not in a voice channel!")
    voice_channel = ctx.author.voice.channel
    if ctx.voice_client is None:
        await voice_channel.connect()
    else:
        await ctx.voice_client.move_to(voice_channel)

@commands.command()
async def disconnect(self,ctx):
    await ctx.voice_client.disconnect()

@commands.command()
async def play(self,ctx,url):
    ctx.voice_client.stop()
    FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    YDL_OPTIONS = {'format':"bestaudio"}
    vc = ctx.voice_client

    with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
        info = ydl.extract_info(url, download=False)
        url2 = info['formats'][0]['url']
        source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
        vc.play(source)

@commands.command()
async def pause(self,ctx):
    await ctx.voice_client.pause()
    await ctx.channel.send("Paused ⏸")

@commands.command()
async def resume(self,ctx):
    await ctx.voice_client.resume()
    await ctx.channel.send("resume ⏯")

def setup(client):
client.add_cog(music(client))```

#

is it just like the commands pause and resume

sick birch
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
waxen python
#

could you listen on the leave channel event and check if it's the bot that left?

#

erm in discord py 2.0 it got changed from icon_url to something else

I want to say icon.url? I can't quite remember

#

check the docs, it might have been changed there

#

something like

    async def on_voice_state_update(self, member, before, after):
torn sail
#

its the same

lyric apex
#

Yep

azure nebula
#
import discord
from discord import app_commands
from discord.ext import commands
from discord import member
from discord.ext.commands import has_permissions, MissingPermissions
import os

class aclient(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            await tree.sync(guild = discord.Object(id = here_goes_guild_id))
            self.synced = True
        print(f'Logged in as {self.user}.')


client = aclient()
tree = app_commands.CommandTree(client)

@tree.command(name="help", description='Help command.', guild = discord.Object(id = here_goes_guild_id))
async def self(interaction: discord.Interaction):
    embed = discord.Embed(name="help", color=0x03f4fc)
    embed.add_field(name='**Example**', value="Hi!.", inline=False)
    embed.add_field(name='**Example**', value="Hello!.", inline=False)
    await interaction.response.send_message(embed=embed)

@tree.command(name="example2", description='Example command.', guild = discord.Object(id = here_goes_guild_id))
async def self(interaction: discord.Interaction):
    embed = discord.Embed(color=0x03f4fc)
    embed.add_field(name='**Example**', value="Example!", inline=False)
    await interaction.response.send_message(embed=embed)

@tree.command(name='example3', description='Example command.', guild = discord.Object(id = here_goes_guild_id))
async def self(interaction: discord.Interaction):
    embed = discord.Embed(color=0x03f4fc)
    embed.add_field(name = "**Example**", value="Example!", inline=False)
    await interaction.response.send_message(embed=embed)```
fading marlin
#

saying "commands don't work" doesn't really help, could you be more specific?

azure nebula
#
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 650, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "c:\Users\USER\Desktop\PC\whocares\main.py", line 26, in self
    embed = discord.Embed(name="Help command", color=0x03f4fc)
TypeError: Embed.__init__() got an unexpected keyword argument 'name'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1157, in call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 675, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 664, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'name'```
azure nebula
#

every other command is working

fading marlin
#

title, not name

azure nebula
#

where

#

oh

#

i see

#

thx

warm lava
#

is this where I can ask discord.py related questions?

#

how

#

async def raid(ctx, arg):
 if arg == 'battle':
 await asyncio.sleep(5)
 await ctx.send("message")
 return 
 #I want this to have a cooldowon so that it can only be used once every minute
#I also want the bot to reset the once every minute cooldown if it detects a message that says "you are not in a raid"

 if arg == 'surrender':
 await ctx.send('surrender message')
 return

#

on both of them?

#

could you explain?

#

I can't understand a thing lol

#

I copied the command example

#

the commands.command

slate swan
#
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 384, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1168, in on_message
    await self.process_commands(message)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1165, in process_commands
    await self.invoke(ctx)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1132, in invoke
    await ctx.command.dispatch_error(ctx, exc)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 552, in dispatch_error
    await injected(cog, ctx, error)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 172, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: [Errno 9] Bad file descriptor``` do one of u know how fix this?
warm lava
#

the invoking part

slate swan
#

or wat part?

warm lava
#

may I dm you?

slate swan
#

thats the thing idk

sick birch
slate swan
#

bc i dont even have a bot.py file

#

but i am using cogs

sick birch
#

How about this, can you post the full traceback?

#

That usually tells us in which file and in what line the issue is happening

slate swan
#
OSError: [Errno 9] Bad file descriptor

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 182, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\cogs\ac.py", line 22, in punishment
    data = getConfig(ctx.guild.id)
  File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\Tools\utils.py", line 33, in getConfig
    updateConfig(guildID, defaultConfig)
  File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\Tools\utils.py", line 44, in updateConfig
    config.write(newdata)
OSError: [Errno 9] Bad file descriptor

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1128, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 899, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 191, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: [Errno 9] Bad file descriptor

During handling of the above exception, another exception occurred:

OSError: [Errno 9] Bad file descriptor

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 166, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\cogs\ac.py", line 75, in punishment_error
    data = getConfig(ctx.guild.id)
  File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\Tools\utils.py", line 33, in getConfig
    updateConfig(guildID, defaultConfig)
  File "C:\Users\0hunintblock\OneDrive\Desktop\testshottas\shottasbot\Tools\utils.py", line 44, in updateConfig
    config.write(newdata)
OSError: [Errno 9] Bad file descriptor

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 384, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1168, in on_message
    await self.process_commands(message)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1165, in process_commands
    await self.invoke(ctx)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1132, in invoke
    await ctx.command.dispatch_error(ctx, exc)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 552, in dispatch_error
    await injected(cog, ctx, error)
  File "C:\Users\0hunintblock\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 172, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OSError: [Errno 9] Bad file descriptor```
sick birch
#

Can you paste utils.py?

slate swan
#

yea

unkempt canyonBOT
slate swan
#

oh shit my bad

#

i forgot

#

@sick birch i think thats it

slate swan
sick birch
#

Regardless of the usecase we can't help you here

slate swan
#

why exactly?

sick birch
#

Because it's against rule 5

sick birch
slate swan
#

the TOS apply if i am making a public bot

#

oh yea naw they can not help u they can get sued and termed

#

its not about u

sick birch
slate swan
#

i havent touched that file in so long

sick birch
slate swan
#

how is youtube gonna sue them for something private and not public

slate swan
#

can i get help there?

sick birch
slate swan
#

then why is it important to join

karmic marsh
#

Hi. I have some working code but I'd like to write it differently and I'm not sure that I can. Here's what I have:

CancelButton = disnake.ui.button(custom_id = "cancelitem", label="Cancel", style=disnake.ButtonStyle.grey)

ConfirmButton = disnake.ui.button(custom_id = "confirmitem", label="Confirm", style=disnake.ButtonStyle.green)

class UI(disnake.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    @CancelButton
    async def cancel(self, input, inter):
        self.value = 0
        self.stop()

        @ConfirmButton
    async def confirm(self, input, inter):
        self.value = 1
        self.stop()
#

and I'd like to move the async def bits up to where the buttons are defined

#

is that possible? how would I do it?

slate swan
#

python >> js my opinion else truth

slate swan
sick birch
# karmic marsh is that possible? how would I do it?

It might be, but if you're looking to keep things together (I assume so, since you're asking how to move it up) you might want to just decorate the function normally without using your @CancelButton and @ConfirmButton

#

Other than that though, th e code is fine

slate swan
slate swan
karmic marsh
slate swan
#

meaning i have better skills in scripting in c++ then i do in python

sick birch
#

Ah, I see. In that case you might want to just subclass disnake.ui.Button

slate swan
sick birch
#

That way you keep everything in one class, and reuse it whenever you'd like

sick birch
karmic marsh
slate swan
#

js is java script

slate swan
karmic marsh
#

"c++ is my better lang" is like "baseball is my better sport" aka "I am better at it" not "it is better"

slate swan
#

da fuck

sick birch
#

You can create that button easily like: MyCustomButton()

#

Reuse as much as you'd like

slate swan
#

didn't know that

slate swan
#

c++ is better

slate swan
sick birch
#

Let's take it down a notch please

karmic marsh
#

that's not at all what I'm saying

slate swan
sick birch
#

Can we not please, and get back on topic?

slate swan
sick birch
#

I'd rather not have to call in the moderators

slate swan
sick birch
#

Seems like it and is also wildly off topic

slate swan
#

i agree but this member is basically saying "if you have a different oppinion than mine then eat shit"

sick birch
#

Ok, how about let's not do that again and move on

slate swan
#

everyone has different opinions and every one should respect that

karmic marsh
sick birch
#

You can use discord.VoiceClient.is_connected() to check if you're connected

karmic marsh
#

disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: expected Item not <class 'abc.ABCMeta'>

sick birch
#

Can i see the code?

karmic marsh
#

here's all of it:

import disnake
from disnake.ext import commands

class CancelButton(disnake.ui.Button):
    def __init__(self, null):
        super().__init__(label="Cancel", style=disnake.ButtonStyle.grey) # construct your button as usual
    async def cancel(self, input, inter):
        self.value = 0
        self.stop()
        #await inter.response.send_message("Cancelled!")

ConfirmButton = disnake.ui.button(custom_id = "confirmitem", label="Confirm", style=disnake.ButtonStyle.green)

class UI(disnake.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None
        self.add_item(CancelButton)

    @ConfirmButton
    async def confirm(self, input, inter):
        self.value = 1
        self.stop()

class Ask(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command()
    async def ask(inter):
        """Asks the user a question to confirm something."""
        layout = UI()
        await inter.send("Do you want to continue?", view=layout, ephemeral = True)
        await layout.wait()
        if layout.value == None:
            await inter.edit_original_message("Timed out", view=None)
        elif layout.value == 0:
            await inter.edit_original_message("Cancelled", view=None)
        elif layout.value == 1:
            await inter.edit_original_message("Confirmed", view=None)

def setup(bot):
    bot.add_cog(Ask(bot))
mossy jacinth
torn sail
flat solstice
#

Hey got a dpy 2.0 question here: so I'm currently creating ext.commands separately from app_commands and I think it would be beneficial to move to hybrid commands.

  1. is there any restrictions what args hybrid commands can take (e,g. will they accept models/forms?)
  2. does the bot will create the default help command with hybrid commands (with or without a slash help command)
slate swan
#

and the callback method takes, self, interaction: discord.Interaction

karmic marsh
#

how does this work when I have multiple methods?

slate swan
#

nor does it make any sense

karmic marsh
#

so then this solution doesn't work for me.

slate swan
#

what's the issue though

karmic marsh
#

I want to have a button and an action that I can add to as many UI Views as I want without having to rewrite them

slate swan
karmic marsh
slate swan
#

I never said anything like that, you might have misunderstood me

karmic marsh
#

probably

slate swan
slate swan
karmic marsh
#

that would be much appreciated lmao

#

I'm going crazy trying to figure this out

slate swan
#

Im on phone so I might be slow but sure

slate swan
#
class ReButton(discord.ui.button):
    def __init__(self):
        super().__init__(label="uwu button", style=discord.ButtonStyle.blue)
     
    async def callback(self, inter: discord.Interaction, button: discord.ui.Button):
        await inter.response.send_message("you clicked me uwu", ephemeral=True)

#adding the button object to a view class

class MyView(discord.ui.View):
     def __init__(self):
          super().__init__(timeout=...)
          self.add_item(ReButton())
slate swan
#

!d discord.VoiceClient.is_connected

unkempt canyonBOT
slate swan
#

you can also do guild.me.voice

karmic marsh
#

(it's surprisingly close to what I had too)

#

I'm just having one issue

#
self.value = 0
#and
self.stop()

no longer point to the parent UI View

slate swan
#

ofc

karmic marsh
#

right

#

I just don't know what I need to change self to

#

or if that's no longer possible

slate swan
# karmic marsh or if that's no longer possible

hm, just declare a var fe self.par_view = view in the __init__

and do self.par_view.stop()

and when you add the button to the view class

self.add_item(ReButton(self))
pass in the instance of the View class using self

#

Now I probably have a broken humour but, why are commands declared in CommandTree using command and not leaf since leaves make food for the plant

tree = CommandTree(client)

@tree.leaf()
async def uwu(): ...```
#

okay i feel bad saying that now

#

my humour is so fucked up

sick birch
#

It’s be a bit misleading to call commands leaves

slate swan
#

boomer robin 😔

sick birch
#

binary search trees do that to you

jagged adder
#

how would i go about writing in a func (not a command) which checks if a user has a role before its called? same effect as if it were a command, but written as a func

sick birch
#

We had quizlets with BST terminology like leaves, nodes, heads, and the formulas for calculating them in comp sci

jagged adder
#

the reason i dont want as a command is so that it cant be called just anywhere; only within a certain part of my code

sick birch
#

Maybe checks are a better way to do that?

slate swan
sick birch
#

They can be reused anywhere

slate swan
sick birch
#

True a check is a basically a function

jagged adder
#

basically im trying to make it so only people w x role are able to use this function which will change a variable in my code

sick birch
#

That’s exactly the intended usecase of a check

#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
sick birch
#

It’s so common that there’s a shortcut check for it

jagged adder
#

can i put this within the func tho ?

#

i was under the impression commands can only be used outside of a func

sick birch
#

Just decorate the commands you want with that decorator

#

I assume you don’t want every single command to be locked to those with that role

jagged adder
#

no; im tryin to set up sleep in parts of my code, and i want only the devs to be able to turn em off

sick birch
#

Yah so just decorate it with the has role check

jagged adder
#

alr

slate swan
karmic marsh
#

yo wait I might have gotten it

#

alright, it's working

#

hey in fact, I can simplify a lot of the other logic too with this parent_property method

#

alright, this works beautifully

#

here's the code:

#
import disnake
from disnake.ext import commands

class CancelButton(disnake.ui.Button):
    def __init__(self, view, inter):
        self.par_view = view
        self.par_inter = inter
        super().__init__(label="Cancel", style=disnake.ButtonStyle.grey)
    async def callback(self,inter):
        await self.par_inter.edit_original_message("Cancelled", view=None)
        self.par_view.stop()

class ConfirmButton(disnake.ui.Button):
    def __init__(self, view, inter):
        self.par_view = view
        self.par_inter = inter
        super().__init__(label="Confirm", style=disnake.ButtonStyle.green)
    async def callback(self,inter):
        await self.par_inter.edit_original_message("Confirmed", view=None)
        self.par_view.stop()

class UI(disnake.ui.View):
    def __init__(self, inter):
        super().__init__()
        self.add_item(CancelButton(self, inter))
        self.add_item(ConfirmButton(self, inter))

class Ask(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command()
    async def ask(inter):
        """Asks the user a question."""
        layout = UI(inter)
        await inter.send("Do you want to continue?", view=layout, ephemeral = True)
        timeout = await layout.wait()
        if timeout:
            await inter.edit_original_message("Timed out", view=None)

def setup(bot):
    bot.add_cog(Ask(bot))
azure nebula
#
@tree.command(name="kick", description='Kicks people from the server.', guild = discord.Object(id = here_goes_guild_id))
async def self(ctx, member : discord.Member, *, interaction: discord.Interaction, reason=None):
    await ctx.member.send(f"You were kicked for: {reason}")
    await member.kick(reason=reason)
    embed = discord.Embed(title = "A user was kicked!", color=0x03f4fc)
    embed.add_field(name="**Kicked user:**", value=f"User {member.mention} was kicked from the server.")
    await interaction.response.send_message(embed=embed)```
azure nebula
# azure nebula ```py @tree.command(name="kick", description='Kicks people from the server.', gu...
  File "c:\Users\USER\Desktop\bots\whocares.py", line 55, in <module>
    async def self(ctx, member : discord.Member, *, interaction: discord.Interaction, reason=None):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 878, in decorator
    command = Command(
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 523, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 383, in _extract_parameters_from_callback
    param = annotation_to_parameter(resolved, parameter)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 700, in annotation_to_parameter      
    (inner, default, validate_default) = get_supported_annotation(annotation)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 659, in get_supported_annotation     
    raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>```
slate swan
#

because you can't have an interaction as a command argument.

azure nebula
shrewd apex
#

meaning async def self(interaction, member, *, reason)

shrewd apex
#

app commands don't have CTX

slate swan
#

they are both 2 different things

#

and only 1 can be used

#

in slash we use interaction

#

and in prefix commands we use ctx

slate swan
#

what was that method name that get called on timeout?

#

any fix for that?

#

targetID is none

slate swan
slate swan
#

ye

slate swan
slate swan
slate swan
slate swan
slate swan
#

or actually not, they describe it as that but do something else inside the function

slate swan
slate swan
slate swan
livid hinge
#

anyone else?

slate swan
slate swan
livid hinge
slate swan
#

!d discord.ui.View.on_timeout

unkempt canyonBOT
#

await on_timeout()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A callback that is called when a view’s timeout elapses without being explicitly stopped.
slate swan
slate swan
livid hinge
#

convention yes

slate swan
#

its just name that gets called

#

no way

#

let me try

shrewd apex
#

how to find degree and cardinality of SQL table ik degree is number of columns is cardinality rows?

slate swan
#

its like on_ready which gets called internally or you can just use the coro and pass the coro obj iirc

shrewd apex
#

thx just being sure

livid hinge
#

not sure ab degrees

boreal ravine
livid hinge
#

google says yes too lol

slate swan
boreal ravine
livid hinge
#

they have interaction ryt

slate swan
boreal ravine
#

they use both, actually

slate swan
#

some libs call it InteractionContext or something along the lines

livid hinge
#

you get parameter for both?

slate swan
#

no its just one

#

its just class naming

#

iirc pycord does it idk

#

i remember pycord doing that, its like a mix of inter and ctx

livid hinge
#

Here’s an example of a slash command:

@bot.slash_command(description="Responds with 'World'")
async def hello(inter):
    await inter.response.send_message("World")```
#

yea looks like

livid hinge
#

ApplicationCommandInteraction

slate swan
#

AppCmdInter works too ( its an alias )

livid hinge
#

oh xD

slate swan
#

disnake has like 4 aliases for that lol

#

@slate swan i ghost pinged you by mistake

slate swan
#

..

unkempt canyonBOT
#

disnake/interactions/application_command.py lines 518 to 525

# People asked about shorter aliases, let's see which one catches on the most
CommandInteraction = ApplicationCommandInteraction
CmdInteraction = ApplicationCommandInteraction
CommandInter = ApplicationCommandInteraction
CmdInter = ApplicationCommandInteraction
AppCommandInteraction = ApplicationCommandInteraction
AppCommandInter = ApplicationCommandInteraction
AppCmdInter = ApplicationCommandInteraction```
slate swan
#

👍

#

the ConnectionState class acts pretty much like the cache manager for discord.py lol

livid hinge
#

Current examples are slash commands, user commands and message commands.

#

huh i didnt know about those others

slate swan
slate swan
#

or a user too iirc

livid hinge
#

can you make custom user commands ?

boreal ravine
slate swan
slate swan
#

markdown in user is typing.... discord ❤️

livid hinge
#

such wow

slate swan
livid hinge
#

is there markdown there lmao

slate swan
slate swan
#

ah💀

slate swan
karmic marsh
#

wait

livid hinge
#

lmao. gotta try smth now

slate swan
#

never knew they used markdown for it

livid hinge
#

maybe some dont ??

slate swan
#

weird

karmic marsh
#

okay... you've got to tell me if this works lmao

slate swan
livid hinge
#

same

karmic marsh
#

can you click it?

slate swan
#

nope

karmic marsh
#

hmm... okay, neat

livid hinge
#

thats hilarious

slate swan
#

its discord so...

karmic marsh
#

that's amazing

boreal ravine
slate swan
#

i feel like thats kinda idk useless or over the top over not using it

livid hinge
#

ʰᵉˡˡᵒ ʷᵒʳˡᵈ

slate swan
#

bro

karmic marsh
#

what did you type

slate swan
#

thats some text in superscript ig?

livid hinge
#

i typed ʰᵉˡˡᵒ ʷᵒʳˡᵈ

alpine pewter
#

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

azure nebula
livid hinge
#

!charinfo ʰᵉˡˡᵒ ʷᵒʳˡᵈ

unkempt canyonBOT
karmic marsh
#

so no special markdown, just special characters?

#

oh.

livid hinge
#

yh

#

sorry to disappoint

#

you got any output ? like traceback

alpine pewter
#

Yep, one sec 😄

#

I'm unsure, sometimes it works, sometimes it doesn't.
It will say "Name is thinking..."

Then sometimes it'll just say it failed immediately.

boreal ravine
#

What happens if you remove the defer?

alpine pewter
#

It's still a 50/50 last I checked.
I changed a few things but I can check one more time

#

It's random when it wants to work, I might've messed something up

boreal ravine
#

It wouldn't affect it unless it's doing something blocking afaik

sullen pewter
#

how to create infractions command

#

do I need to use a database?

alpine pewter
#

Unless, can you not do that with followup.send?

slate swan
topaz wraith
#

can anyone send me the code of making a music bot?

#

from python ofc

slate swan
#

!ytdl to see why it breaches the TOS

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
topaz wraith
slate swan
#

your question should be why are so many big music bots are now becoming unfunctional

topaz wraith
#

plus, can't we use spotify?

slate swan
#

hydra doesn't support any sounds from YouTube anymore

#

they are making themselves limited

topaz wraith
#

oh

#

anyways, can't we use spotify?

maiden fable
#

No

slate swan
#

Spotify haven't taken down any bot for using their API for playing music yet but they have similar ToS, all services do

maiden fable
shrewd apex
maiden fable
#

They allow streaming music as long as u follow their ToS

topaz wraith
#

so basically, we can use spotify, right?

shrewd apex
#

u can even use ytdl but we wont provide help for either

maiden fable
slate swan
#

Improper use. Do not improperly access, alter or store the Spotify Service or Spotify Content, including
using any robot, spider, site search/retrieval application, or other tool to retrieve, duplicate, or index any portion of the Spotify Service or Spotify Content (which includes playlist data) or collect information about Spotify users for any unauthorized purpose;

shrewd apex
#

nope nvm me

maiden fable
#

Soundcloud allows streaming music bruv

slate swan
#

SoundCloud allows you to use its api freely, just don't download the songs, cache them instead

maiden fable
#

Yes

slate swan
#

whos gonna download them anyways lol

maiden fable
#

Indeed

shrewd apex
#

just listen from spotify discord isnt even a legit music streaming software

maiden fable
#

I back him. If u got Spotify, why even use a VC lol

sullen pewter
maiden fable
#

Instead of sitting in the VC and listening to song, go touch grass

sullen pewter
#

unexpected keyword argument

maiden fable
slate swan
#

view is a kwarg in send

sullen pewter
#

ty

dim sentinel
#
def pi(x:str,y:int):
    return x*y

@spi.command()
async def ping(ctx,x:str,y:int):
    pong=pi(x,y)
    await ctx.send(pong)

basically i want it to be a ping machine but it only sends the number of pings in one message

#

i want to send string*int but each time the result in different line

#

can someone help?

topaz wraith
#

but basically you guys are telling, your not gonna help me make the music bot, right?

dim sentinel
#

someone help with mine atleast 😭

shrewd apex
#

u could just do for i in range(y): await ctx.send(x)

topaz wraith
#

ok

#

bye then ig

slate swan
dim sentinel
#

each time diff ping to the person

paper sluice
slate swan
unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

001 | apple
002 | apple
003 | apple
maiden fable
#

"\n".join(string*number)

shrewd apex
#

he wanted like 3 pings ig

maiden fable
#

Weird

slate swan
dim sentinel
maiden fable
#

Then Asher is correct

dim sentinel
#

@dim sentinel

maiden fable
paper sluice
slate swan
shrewd apex
#

is it so hard to read the first answerlemon_angrysad

dim sentinel
shrewd apex
#

lmao

slate swan
shrewd apex
#

lol

#

ic

left idol
#

is it possible to have more than 25 option choices?

shrewd apex
#

i dont think so

#

atleast not in one message

dim sentinel
#
@spi.command()
async def ping(ctx,x:str,y:int):
     i in range(y)
     await ctx.send(x)
``` it says i is not defined, I am sure i am doing something wrong here
left idol
#

ah that sucks, i was trying to pass through 32 options

slate swan
#

why tf?

left idol
#

different teams

shrewd apex
#

32 teams...

dim sentinel
slate swan
#

how would that work?

dim sentinel
#

sorry for the ping

left idol
#

i just wanted a nicer way for them to input which team

shrewd apex
#

smh guy still cant scroll up and read

slate swan
#

I'd just do py async def foo(inter, team, value): ...

left idol
#

and lower chances of messing up

shrewd apex
slate swan
left idol
#

can i instead make it autocomplete

#

if you give in a argument

shrewd apex
#

use difflib

slate swan
#

i mean autocomplete is not even important when discord gives a better option called choices

#

so they'll never be able to use any invalid team

left idol
#

wym

slate swan
#

only the teams you allow will be allowed to input in that field

shrewd apex
slate swan
#

like in thise option i have, the choices come up automatically

left idol
#

i am using slash commands

#

yeah

slate swan
#

in case someone enters an invalid one, the get an error on their side

left idol
#

so i should always opt to use option choices because it eliminates error?

#

for things where it has to match a value

slate swan
#

yep that would be more Efficient than having 32 options

left idol
#

ok, i will probably split my choices into groups of 4 then

dim sentinel
#

so sorry to even trigger you there

#

my bad

#

Also am i gonna get rate limited now 😃

#

for this spam

shrewd apex
#

yeah if u cross a certain threshold of y

dim sentinel
shrewd apex
#

idrk i think it was like 28 message i think per sec?

#

ask sarth

dim sentinel
#

it's one ping per sec

#

or more than that

#

it's definately not 25 pings per sec

shrewd apex
#
All bots can make up to 50 requests per second to our API. This is independent of any individual rate limit on a route. If your bot gets big enough, based on its functionality, it may be impossible to stay below 50 requests per second during normal operations.
dim sentinel
#

so it's not gonna get ratelimited right?

sullen pewter
#
 @discord.ui.button(label='Verify', style=discord.ButtonStyle.green)
    async def callback(self, interaction: discord.Interaction, button: discord.ui.Button):
        name = 985055853096886283
        member = interaction.user
        role = discord.utils.get(member.guild.roles, id=name)
        await member.add_roles(member, role)
        await interaction.response.send_message(embed = discord.Embed(f"Welcome! {interaction.user.name}, you have been granted {role.name} role!", color = discord.Colour.green))

        self.value = True
        self.stop()```
#

Error: Unknown role

#

Assigns role on interaction

slate swan
topaz wraith
slate swan
#

woah

sullen pewter
#

what should I do

topaz wraith
slate swan
# sullen pewter why

oh nvm, role is fine, interaction.user returns a User object (use interaction.member instead)

slate swan
#

nice.

topaz wraith
#

ok

left idol
#

i can't have optionchoices inside of the command?

#

i want it to display different options if you input specific groups

#
groops = [
    OptionChoice(name = "A", value = "A"),
    OptionChoice(name = "B", value = "B"),
    OptionChoice(name = "C", value = "C"),
    OptionChoice(name = "D", value = "D"),
    OptionChoice(name = "E", value = "E"),
    OptionChoice(name = "F", value = "F"),
    OptionChoice(name = "G", value = "G"),
    OptionChoice(name = "H", value = "H"),
]
@bot.slash_command(description = "Change teams for user")
@commands.has_role("Captain")
async def team(ctx, player: discord.User, team: discord.Option(str, choices=choose), group: discord.Option(str, choices=groops), tmz: str):

    if group == 'A':
        choose = [
        OptionChoice(name = "Tokyo Fart Sniffers", value = "Tokyo Fart Sniffers"),
        OptionChoice(name = "Robstown Somethings", value = "Robstown Somethings"),
        OptionChoice(name = "Baltimore Bughas", value = "Baltimore Bughas"),
        OptionChoice(name = "London BC", value = "London BC")
        ]
    elif group == 'B':
        choose = [
        OptionChoice(name = "Neko Cavaliers", value = "Neko Cavaliers"),
        OptionChoice(name = "Xinzhou Warriors", value = "Xinzhou Warriors"),
        OptionChoice(name = "Kyoto Kings", value = "Kyoto Kings"),
        OptionChoice(name = "Charlotte Stingers", value = "Charlotte Stingers")
        ]

for example?

lyric apex
#

How to add multiple emojis?

shrewd apex
#

finally done verification with GitHub student🎉

lyric apex
vocal snow
shrewd apex
#

thx

shrewd apex
lyric apex
lyric apex
#

I wanted that if there is mentioned 2-3-4 emoji then it adds them

slate swan
#

use a for loop and add them

lyric apex
#

Any other options?

slate swan
#

nope

lyric apex
#

In discord.PartialEmoji How To use from_str method? @slate swan

#

!d discord.PartialEmoji

unkempt canyonBOT
#

class discord.PartialEmoji```
Represents a “partial” emoji.

This model will be given in two scenarios:

• “Raw” data events such as [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add")

• Custom emoji that the bot cannot see from e.g. [`Message.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.reactions "discord.Message.reactions")...
vale wing
#

Basically a classmethod

#

Alternative constructor

#

!d discord.PartialEmoji.from_str

unkempt canyonBOT
#

classmethod from_str(value)```
Converts a Discord string representation of an emoji to a [`PartialEmoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PartialEmoji "discord.PartialEmoji").

The formats accepted are...
vale wing
#

I believe like this

emoji = PartialEmoji.from_str(":bruh:")  # idk if I wrote the form correctly, prolly not```
lyric apex
#

PartialEmoji Is Not Defined

vale wing
#

Do some experiments and see what kind of emojis you can convert

vale wing
lyric apex
#

?how

vale wing
vale wing
#

That's way too obvious question

lyric apex
vale wing
#
from discord import PartialEmoji
# OR
import discord
discord.PartialEmoji```
lyric apex
#

It is correct?

vale wing
#

You would better just typehint emoji with discord.Emoji

lyric apex
#

Lemmie Try

vale wing
#

And you would have no need to convert them in code

#
async def lol(ctx, *emojis: discord.Emoji)```
lyric apex
vale wing
lyric apex
#

Command raised an exception: TypeError: '<' not supported between instances of 'PartialEmoji' and 'PartialEmoji'

shrewd apex
#

*args gives a tuple in discord

lyric apex
vale wing
shrewd apex
#

*, args will give a string

vale wing
#

By what are you gonna sort them

vale wing
shrewd apex
vale wing
#

That's a different thing

vale wing
shrewd apex
#

why even sort in first place

vale wing
#

Yes

#

If you really wanna sort them you need to sort them by something comparable

#

Emojis themselves are not comparable

#

Like if you wanna sort by name you would have to do something like this

sorted(emojis, key=lambda x: x.name)```
lyric apex
#
Command raised an exception: AttributeError: type object 'PartialEmoji' has no attribute 'from_str'```
#

But why this?

vale wing
#

You probably have dpy 1.7 and it was added in 2.0

lyric apex
#

Ahh no way for 1.7?

vale wing
#

Why didn't you just typehint like I said

slate swan
#

!d discord.ext.commands.PartialEmojiConverter.convert use this

unkempt canyonBOT
#

await convert(ctx, argument)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will properly propagate to the error handlers.
vale wing
#

Why not just typehint, essentially the same thing

slate swan
#

though typehinting is the better way

left idol
#

how can i make an embed field start in another row?

vale wing
#

I think you mean something like inline

#

!d discord.Embed.add_field set inline to False

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
opal dove
#

Is there a way to input user discord roles to google sheets?

vale wing
#

If google sheets has a public API then yes

shrewd apex
vale wing
#

And yeah I recommend using aiohttp instead of their wrappers because as I can see they are sync

opal dove
dim sentinel
#
@spi.command()
async def ping(ctx,x:str,y:int):
    if y>100:
        await ctx.send("> :x: **The maximum limit is 100**")
    else: 
        for i in range(y):
             await ctx.send(x) 

I want to break the loop by using a command

#

can someone answer this one?

shrewd apex
#
@spi.command()
async def ping(ctx,x:str,y:int):
    if y>100: return await ctx.send("> ❌ **The maximum limit is 100**")
    for i in range(y): await ctx.send(x)
#

u can disable the command ig not really sure

short silo
#
async def kick(ctx,
               member: Option(choice=discord.member,description="Tag the member"),
               reason: Option(str,description="Reason",default="None")):

I am using this, yet in member, any input can be given. How to fix that ?

spring flax
#

for a discord bot, how would I implement this

subreddit = await reddit.subreddit("mod")
async for item in subreddit.mod.stream.reports():
    await channel.send(item)

this was in the example page. It says that it yields reports once they become available. So where can I put this in if I want the bot to alert on each report?

spring flax
#

Yeah...but the docs say it yields once the report is available

#

So.. I guess that works

spring flax
#

is there no way to just have this like it is

subreddit = await reddit.subreddit("subreddit")
async for item in subreddit.mod.stream.reports():
    print(item)

#

like not in a loop or a command or anything

maiden fable
#

Sorry, ain't got an idea

spring flax
#

My lint says no do guess not. I'm just not sure what the time in between loop should be

#

Unless I do bot.run_until_complete

magic pond
#

can my bot find if a user has nitro badge in his profile ?

heady sluice
#

!d discord.User.public_flags

unkempt canyonBOT
heady sluice
#

why do I not see the nitro one here

maiden fable
heady sluice
#

what's the difference between seeing the hypesquad badges and a nitro badge

spring flax
#

If you have an idea

maiden fable
#

Do u mean bot.loop.run_until_complete?

spring flax
#

Ah yes my bad

maiden fable
#

Why u calling that tho?

spring flax
#

Tbh I'm not entirely sure what it does lol

#

Is there a way to call it continuously (continuous loop)

heady sluice
quick gust
#

ask them the same question

heady sluice
#

where

slate swan
heady sluice
#

the badge

#

not how you get it

#

when you have both of them

#

the way you get them

#

but I'm not asking shit in a server of Danny

#

those are all toxic

slate swan
#

you buy nitro, you submit a form for hypesquad

heady sluice
#

not how you get it,
the way you get them

#

my logic is on top

slate swan
#

makes the same sense, you are contradicting yourself now-

heady sluice
#

no

#

I said the same thing with different meanings

#

why can't you read my mind

slate swan
#

I'm not you, and you're not mine me

heady sluice
#

you're not not mine

#

so I'm yours

paper sluice
heady sluice
#

Hunter's going to ot tag us

tawdry perch
#

!ot

short silo
#
async def kick(ctx,
               member: Option(discord.Member,description="Tag the member"),
               reason: Option(str,description="Reason",default="None")):
    guild = ctx.guild
    embed = Embed(title="Processing...",color=Colour.blue())
    og_interaction = await ctx.response.send_message(embed=embed,ephemeral=True)
    if member.top_role > ctx.author.top_role:
        embed=Embed(title="You can only kick users with a lower role!",color=Colour.red())
        await og_interaction.edit_original_messsage(embed=embed)

edit_original_message is wrong ?

timber forum
#

Anyone?

slate swan
#

i make on reaction add create ticket but i dont know how can i create if channel already have name discord.py

#

any who can help

jagged adder
#

i have a class that contains self.sleep = False, however when i try to call the variable, it brings up this error

AttributeError: 'NewGameState' object has no attribute 'sleep'

i have no clue as to why tho

#

every other variable in the class seems to work, except not this one

brazen raft
#

You can't call False

#

But that doesn't even seem to be the issue

jagged adder
#

i tried changing it to True, still didnt work

paper sluice
jagged adder
#

yeah

brazen raft
#

Where have you defined self.sleep in the class

#

In __init__?

jagged adder
#

yeah, like so

class NewGameState:
    def __init__(self):
        self.sleep = False
#

trying to call it in an if statement

#
        if state.sleep:
            await asyncio.sleep(3)
brazen raft
#

Do you have del state.sleep in your code

jagged adder
#

not as far as im aware

brazen raft
#

What is state defined as

#

state = NewGameState?

#

It should be defined as state = NewGameState()

#

Calling a class creates an instance of it, state = NewGameState just assigns it another name

paper sluice
brazen raft
#

This does not work because NewGameState is a class object, not an instance object of a class

jagged adder
#

yeah my code got a bunch of renaming going on

brazen raft
brazen raft
#

Class objects don't have the attributes of their instances

jagged adder
#

yeah its set up like so

ctx.bot.game_states[str(game_channel.id)] = NewGameState()

state = ctx.bot.game_states[str(game_channel.id)]
brazen raft
#

See this

>>> class GameState:
...     def __init__(self):
...         self.should_sleep = False
... 
>>> game_state_instance = GameState()
>>> game_state_instance.should_sleep
False
>>> 
brazen raft
jagged adder
#

yep

brazen raft
#

Well then what is ctx in both of those files

#

Also it might be that you forgot to put parentheses somewhere else in your code and it's trying to access that

slate swan
#

@bot.event async def on_reaction_add(reaction, user = None): if '**🚀 ┇ SUPPORT**\n\n ► If you have any question\n ► If you need any help\n ► Open ticket with reaction on this message\n\n ╭ Spamming in ticket is disabled\n ┊ Ghost ping in ticket is disabled\n ┊ Multiple tickets are not allowed\n ╰ Opening for no reason is disabled' in reaction.message.embeds[0].description and reaction.emoji == '👾' and not user.bot: role = discord.utils.get(user.guild.roles, name="@everyone") chan = await user.guild.create_text_channel(name=f'ticket - {user}') await chan.set_permissions(role, send_messages=False, read_messages=False, add_reactions=False, embed_links=False, attach_files=False, read_message_history=False, external_emojis=False) await chan.set_permissions(user, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True) embed = discord.Embed(description="**🚀 ┇ SUPPORT**\n\n ► Thanks for open ticket\n ► Now wait for a response from owners") embed.set_footer(text="†  Creator Matija#4633 † ") msg = await chan.send(embed=embed)

#

How can i disable multiple channel create

spring flax
#

!code

unkempt canyonBOT
#

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.

swift imp
#

How to create whitelist channels?
I did something like this:```py
WHITELISTED_CHANNELS = ["123", "124"]

@bot.check
def check_commands(ctx):
return ctx.author.id in WHITELISTED_CHANNELS```
But it doesn't work

misty stream
#

Hi i have a question
i have this 8ball script
and i want to make it so that if you do just !8ball it will return a message with you need to include a question
how do i do that ?
because right now it just returns
message is a required argument that is missing.
in the console

@commands.command(aliases=['8ball'])
    async def eightball(self, ctx, *, message:str):
        if message == '':
            await ctx.send("Please include a question like : 8ball questionhere")
lyric apex
misty stream
#

okey ill try that

rocky hornet
#

what is MessageReference.resolved and when should i use it?

misty stream
cloud dawn
# misty stream Hi i have a question i have this 8ball script and i want to make it so that if ...
from discord.ext.commands import Context, CommandError, MissingRequiredArgument

@commands.command(aliases=['8ball'])
async def eightball(self, ctx: Context, *, message: str) -> None:
    await ctx.send(message)

@eightball.error
async def eightball_error(self, ctx: Context, error: CommandError) -> None:
    if isinstance(error, MissingRequiredArgument):
        await ctx.send("Please include a question like : 8ball questionhere")
lyric apex
#

Zz_okie ||pandabweer|| was writing paragraph

cloud dawn
rocky hornet
#

this isnt descriptive

#

you just copy pasted this from the docs

cloud dawn
misty stream
#

i didnt even know @eightball.error was a thing !

lyric apex
#

if not message:

cloud dawn
cloud dawn
rocky hornet
#

what is """""""""""resolve"""""""""""""

lyric apex
#

||Zz_okie ||

fading marlin
cloud dawn
lyric apex
#

If it is not mentioned True It is true by default yetZz_okie

cloud dawn
halcyon basalt
#
import discord 
import random
from discord.ext import commands
from discord_slash import SlashCommand



bot  = commands.Bot(command_prefix="!", description = "tools dev by zcronic")
slash = SlashCommand(bot, sync_commands= True)

@bot.event
async def on_ready():
    print("ready")

@slash.slash(name="size_femme", guild_ids=[916447427605725194], description="voir les tailes femme us en eu ")
async def size_femme (ctx):
    await ctx.send("https://www.sports-loisirs.fr/img/cms/guides%20pointure/Pointures-femme-Nike.jpeg")


@slash.slash(name="size_homme", guild_ids=[916447427605725194], description="voir les tailes homme us en eu ")
async def size_homme (ctx):
    await ctx.send("https://www.sports-loisirs.fr/img/cms/guides%20pointure/Pointures-homme-nike.jpeg")


@slash.slash(name="raffle", guild_ids=[916447427605725194], description="voir les sites qui prélèvent ou non lors de raffle")
async def raffle (ctx):
    embed =  discord.Embed (title = ("Guides des prélevements pour les raffles"),description = ("-"))
    embed.add_field(name = ("__sites qui prélèvent__"),value=("-afew\n" "-consortuim\n""-Cornerstreet\n""-Footpatrol\n" "-GrosBaskets\n" "-Hanon\n" "-kickz\n" "-JD sport\n" "-Seventstore\n" "-size\n" "-Slam Jam\n"))  
    embed.add_field(name = ("__sites qui ne prélèvent pas__"),value=("-Basket4Ballers\n" "-BSTN\n""-Courir\n""-END\n" "-Fenom\n" "-Footshop\n" "-Goodhood\n" "-Kith\n" "-Noirfonce\n" "-One Block Down\n" "-shinzo\n"  "-Sivasdescalzo\n" "-SNS\n" "-4 elementos\n" ))
    await ctx.send(embed = embed)```
cloud dawn
#

I've got no clue what requires_var_positional is that just seems like it's made up.

lyric apex
halcyon basalt
lyric apex
fading marlin
unkempt canyonBOT
cloud dawn
rocky hornet
#

but this isnt an async method

halcyon basalt
rocky hornet
#

so resolved is set as a side effect of other methods?

cloud dawn
cloud dawn
unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

halcyon basalt
cloud dawn
rocky hornet
#

this shit is very confusing

#

I've made this thing

halcyon basalt
rocky hornet
#

is it usable?

cloud dawn
cloud dawn
rocky hornet
halcyon basalt
cloud dawn
rocky hornet
#

not gonna use unstable libs

halcyon basalt
rocky hornet
#

especially with such an arrogant creator

cloud dawn
rocky hornet
#

no i made this to get the replied to message

#

but .resolved confuses me

vale wing
#

I still don't get what does := do

rocky hornet
#

ref.cached_message or ref.resolved or await self.channel.fetch_message(ref.message_id)

rocky hornet
cloud dawn
cloud dawn
rocky hornet
vale wing
#

Ok got it

cloud dawn
rocky hornet
#

wut