#discord-bots

1 messages · Page 1091 of 1

shrewd apex
#

then just do message.channel.send

scarlet aurora
#

ye i got it now ty

paper sluice
#

on_event event 😳 😳

shrewd apex
#

is pycharm modded professional worth getting?like should i download ?

slate swan
#

just get github students plan and use it legally

shrewd apex
#

what that i dont use git for much except backup data or git cli for herokupithink

slate swan
#

doesnt matter, all it needs is

  1. a github account
  2. a proof that you're a student.
shrewd apex
#

do they give free stuff?

slate swan
#

thats all

paper sluice
slate swan
slate swan
topaz wraith
#

Is this the correct code to

  1. Give the user a warn
@client.command()
@commands.has_permissions(administrator=True)
async def warn(ctx, user: discord.Member,*,reason=""):
  if reason == "":
    embedVar8 = discord.Embed(
      title=(f"Error"),
      desription=("Please specify a reason!"),
      colour=(0xff0000))
    await ctx.channel.send(embed=embedVar8)

  else:
    embedVar9 = discord.Embed(
      title=('**User Warned**'),
      description=(f'{user} has been warned because: {reason}'),
      colour=(0xff0000))
    user_id = str(user.id)

    if user_id in db:
      db[user_id].append(reason)
    else:
      db[user_id] = [reason]
    await ctx.channel.send(embed=embedVar9)
  1. Delete the mentioned warn a user has
@client.command()
@commands.has_permissions(administrator=True)
async def deletewarn(ctx, user: discord.Member,*, n):
 embedVar11 = discord.Embed(
   title=(f"Removed warn of {user.name}"),
   description=(f"Warn {n} of {user} removed!"),
   colour=(0xff0000))
  if user_id in db:
      db[user_id].pop(reason)
    await ctx.channel.send(embed=embedVar10)
  1. Show the list of warnings the user has
@client.command()
@commands.has_permissions(administrator=True)
async def warnings(ctx, user: discord.Member):
  warnlist = db[str(user.id)]
  embedVar10 = discord.Embed(
    title=(f"Warnings of {user.name}"),
    description= "\n".join(f"{i}) {r}" for i, r in enumerate(warnlist, 1)),
    colour=(0xff0000))
  await ctx.channel.send(embed=embedVar10)

Hey, this is my command, Please see if its correct

slate swan
#

yeah cause you sent a message object

paper sluice
scarlet aurora
#

oh ok

slate swan
#

you are looking for message.content maybe

scarlet aurora
#

how can i send the message not the object

#

ah yes ty

slate swan
topaz wraith
slate swan
#

Please tell me why he combines the nickname and the reason in one message and displays an error?

paper sluice
topaz wraith
slate swan
paper sluice
#

xD

shrewd apex
#

my school is not therelemon_angrysad

paper sluice
slate swan
#
    @commands.has_role(982744620792426537)
    @commands.command(name = "бан", aliases = ["забанить", "ban"])
    async def command_clear(self, ctx, *, member: discord.Member, reason):

        try:
            await ctx.channel.purge(limit = 1)
            # await member.ban(reason=reason)
            
            memberName = member.name
            memberTag = member.discriminator
            author = ctx.author.name
            tag = ctx.author.discriminator

            embed = discord.Embed(
                title=(f"Был забанен {memberName}#{memberTag}")    ,
                color= 0xff0000
            )

            embed.set_footer(
                text="| Правительство SK",
                icon_url= ctx.guild.icon_url,
            )

            file1 = discord.File("./ImageS/user_card.png")

            embed.set_image(url='attachment://user_card.png')

            date = datetime.datetime.today()

            embed.add_field(name="Бан выдан:", value= (f"{author}#{tag}"), inline=True) 
            embed.add_field(name="Срок бана:", value="2 дня", inline=True) # по очереди потомучто в конце True
            embed.add_field(name='\u200b', value='\u200b', inline=False)
            embed.add_field(name="Причина Бана:", value=reason, inline=True) 
            embed.add_field(name="Дата выдачи:", value= date.strftime('%d-%m-%Y %H:%M:%S'), inline=True)

            await ctx.send(file=file1, embed=embed)
            os.remove("./ImageS/user_card.png")
slate swan
scarlet aurora
#

problem, my bot is having an epileptic fit, whenever a keywork is typed, the bot types out the content but then it detects it and deletes it, and then this just cycles

shrewd apex
#

ik just sad...

scarlet aurora
#

how do I make the bot ignore itself

shrewd apex
#

if bot.user: return

slate swan
#

if message.author == bot.user

scarlet aurora
#

oh k thanks

shrewd apex
#

lemme get my id card

verbal glacier
#

how to make the role for clicking on the reaction, but give it to those who have 100 messages on the server, and those who have not typed the error message

scarlet aurora
#
        if 'lol' or 'yes' or 'noob' or 'woah' in message.content:``` Why does this detect every message that is sent, even if it's not one of those words, even if its a number??
shrewd apex
#
Non-US State or CA Province
unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
shrewd apex
paper sluice
#

ca is related to canada i think

scarlet aurora
#

oh ok thanks

shrewd apex
#

ok done

shrewd apex
scarlet aurora
# paper sluice non-us maybe?
if message.content in ('aye'):``` this does not work because if a message is like "aye wassup" it wont detect it, the message has to litteraly just say "aye"
shrewd apex
#

'aye' in message.content

#

u check if there is a apple in a basket not the other way arnd

scarlet aurora
#

oh yes

topaz wraith
#

Is this the correct code to

  1. Give the user a warn
@client.command()
@commands.has_permissions(administrator=True)
async def warn(ctx, user: discord.Member,*,reason=""):
  if reason == "":
    embedVar8 = discord.Embed(
      title=(f"Error"),
      desription=("Please specify a reason!"),
      colour=(0xff0000))
    await ctx.channel.send(embed=embedVar8)

  else:
    embedVar9 = discord.Embed(
      title=('**User Warned**'),
      description=(f'{user} has been warned because: {reason}'),
      colour=(0xff0000))
    user_id = str(user.id)

    if user_id in db:
      db[user_id].append(reason)
    else:
      db[user_id] = [reason]
    await ctx.channel.send(embed=embedVar9)
  1. Delete the mentioned warn a user has
@client.command()
@commands.has_permissions(administrator=True)
async def deletewarn(ctx, user: discord.Member,*, n):
 embedVar11 = discord.Embed(
   title=(f"Removed warn of {user.name}"),
   description=(f"Warn {n} of {user} removed!"),
   colour=(0xff0000))
  if user_id in db:
      db[user_id].pop(reason)
    await ctx.channel.send(embed=embedVar10)

Are these code correct?? I think 2nd one is wrong

scarlet aurora
shrewd apex
#

-_-

scarlet aurora
#

nvm i got it

#

it's just repetitive af

shrewd apex
#

hah

slate swan
#

lol

#

!e ```py
content = "hewoooo baka"
words = ("hey", "baka")
if any(content.contains(word) for word in words):
print("works")

unkempt canyonBOT
#

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

works
topaz wraith
#

please help me

shrewd apex
#

lmao

#

yeah

slate swan
scarlet aurora
topaz wraith
scarlet aurora
shrewd apex
paper sluice
scarlet aurora
slate swan
paper sluice
shrewd apex
#

!e

word = 'baka'
words = ['baka', 'bakabaka']
if word in words:
    print('baka')
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your eval job has completed with return code 0.

baka
shrewd apex
paper sluice
scarlet aurora
#
        baka = ["e"]

        if baka in message.content:```
slate swan
scarlet aurora
#

mine dont work if baka in message.content: TypeError: 'in <string>' requires string as left operand, not list

paper sluice
#

__contains__ is a function, so it has to look it up and call it. in is keyword so its just direct call

shrewd apex
#

lmao at first i just looked at the decimal points

scarlet aurora
#

bro it doesn't work the way i want it

topaz wraith
#

!e

@client.command()
@commands.has_permissions(administrator=True)
async def deletewarn(ctx, user: discord.Member,*, n):
 embedVar11 = discord.Embed(
   title=(f"Removed warn of {user.name}"),
   description=(f"Warn {n} of {user} removed!"),
   colour=(0xff0000))
 if user_id in db:
      db[user_id].pop(reason)
  await ctx.channel.send(embed=embedVar11)
scarlet aurora
#

it only detects it if the message is only "e"

shrewd apex
#

it wont work the way u want just coz u want it u have to code it that way smh

unkempt canyonBOT
#

@topaz wraith :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 10
002 |     await ctx.channel.send(embed=embedVar11)
003 |                                             ^
004 | IndentationError: unindent does not match any outer indentation level
shrewd apex
#

why are u trying to eval a discord command?

topaz wraith
#

uh, idk

slate swan
#

i wonder why didnt it raise an error for @client.command tho lmao, isnt client not defined here

shrewd apex
#

sometimes i just wonder am i that bad at explaining 🥲

slate swan
#

!e client

maiden fable
granite parcel
#

how to check user has nitro or not

slate swan
maiden fable
unkempt canyonBOT
slate swan
topaz wraith
#

!e

@client.command()
@commands.has_permissions(administrator=True)
async def deletewarn(ctx, user: discord.Member,*, n):
 embedVar11 = discord.Embed(
   title=(f"Removed warn of {user.name}"),
   description=(f"Warn {n} of {user} removed!"),
   colour=(0xff0000))
 if user_id in db:
      db[user_id].pop(reason)
await ctx.channel.send(embed=embedVar11)
unkempt canyonBOT
#

@topaz wraith :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 10
002 | SyntaxError: 'await' outside function
topaz wraith
#

lol

fiery sphinx
#

.

topaz wraith
#

but this command is not working

#

it shows "undefined 'user_id' "

shrewd apex
topaz wraith
#

no, i have defined it as user_id

#

oh wait'

#

i did it before this

#

this might work

frozen patio
#

The modules won’t load to get the prefixes for the servers

fallow mauve
#

so in javascript you have this thing where you can do this:

/.note./
```how is this done in python where only the taxt in bwtween the slashes is set as a not and you can still write code after it
granite parcel
shrewd apex
#

'''

#

for multiline comments

fallow mauve
#

i dont get it


'''thing here?'''

maiden fable
slate swan
#

im kinda sure its either js // this is a comment, or /* this is a comment */ in js , nothing like /. ./ exists

topaz wraith
#

nope, not working

granite parcel
maiden fable
granite parcel
#

but that will be wrong for others

shrewd apex
#

sigh

fallow mauve
scarlet aurora
#

@slate swan py if any(message.content.__contains__(baka) for baka in message.content):

#

dis no work

shrewd apex
#

dosent this just check for whether message elements are present in message?

scarlet aurora
#

the problem is it just detects every single message

#

sent, not even the messages in baka

shrewd apex
#

message.content here should be the list of blacklisted words

maiden fable
#

Hey @crisp drift apologies for the ping, but how can I set the propagate to False? I am using getLogger() rn, so I should do getLogger().propagate=False or access the basicConfig?

scarlet aurora
#

so message.content should be baka?

shrewd apex
#
if any(message.content.__contains__(baka) for baka in ['''blacklisted words''']):
scarlet aurora
#

baka is the blacklisted words though

maiden fable
#

Nice, I like it when someone uses direct dunders

shrewd apex
#

looks cool

scarlet aurora
#

alright it works thanks

shrewd apex
#

makes it look out of convention kinda

#

sarth how long did it take for u to get the application approved

rare saddle
#

How to get the time of writing the last message from the participant and compare it, let's add 4 hours to the time of writing the message and make a check

maiden fable
crisp drift
shrewd apex
maiden fable
shrewd apex
#

even if ask for 2.0 doc link in help channel says go take it playground

crisp drift
#

You need to instantiate Logger first

maiden fable
#

Yea logger = getLogger()

crisp drift
#

Yes

maiden fable
#

Thankss!

crisp drift
#

You can also do logging.StreamHandler() to add your handler @maiden fable

slate swan
#

?tag search <tag_to_find>

shrewd apex
#

yeah but too lazy to search

#

better to ask

slate swan
#

?rtfm lastest <feature> ease

shrewd apex
#

i searched 2.0 once and got like a 100 tags

shrewd apex
slate swan
#

nice

vocal plover
#

I get the joy of being hated by most dpy regulars who have never met me kek

shrewd apex
#

how was ur cs exams went good?

fallow mauve
#

any idea how to fix code where yesterday discord.ui buttons was working but now it says discord.ui isnt a thing?

sick birch
#

It somehow downgraded to 1.7 overnight then

fallow mauve
slate swan
sick birch
#

Use docker 👍

cloud dawn
vocal plover
#

Being a fork maintainer has the advantage of dpy hardcore fans hating you for no good reason

fallow mauve
shrewd apex
sick birch
#

Docker is good since your libraries don’t magically downgrade

#

Or venvs too I suppose

fallow mauve
shrewd apex
vocal plover
#

just pinning dep versions with pip even

cloud dawn
shrewd apex
#

do they downgrade even?

#

like the lib just had a mood and depreceated themselves or rolled back?

rare saddle
#

How to create a thread from a member's post?

slate swan
#

len(self.client.users) work to get all the users the bot knows?

maiden fable
maiden fable
slate swan
#

and possible to get total commands in the bot?

shrewd apex
#

self.client.commands

shrewd apex
slate swan
#

how to get creation date of my bot?

rare saddle
slate swan
# maiden fable Why

you do know how much we all hate the dpy server not to mention I sometimes do help there

shrewd apex
#

self.client.created_at

#

ig something similar not sure

#

user has a created at object should work with bot too

#

yeah created_at

slate swan
#

!d discord.ClientUser.created_at

unkempt canyonBOT
#

property created_at```
Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.
shrewd apex
#

np

slate swan
shrewd apex
#

yeah

shrewd apex
maiden fable
shrewd apex
#

i tried to help there too but most problems were either intents or just python venv stuff

maiden fable
shrewd apex
#

atleast add a hint

maiden fable
shrewd apex
#

ah the process_commands as well

maiden fable
#

And a common solution-

  1. Enable message content intents from DDevs Portal
  2. Enable it in your code
maiden fable
slate swan
#

Is there an event for invites?

slate swan
alpine cove
alpine cove
slate swan
#

I’m in a cog

slate swan
#

’Bot’ object has no attribute ‘created’

#

💀CoolKid

crisp drift
# maiden fable How?

Pass it to the module. I don't really deal that much with logger so I'm not an expert with it neither

slate swan
unkempt canyonBOT
fallow mauve
#

@sick birch could you go over how docker works? bcs im really lost here

alpine cove
#

wrong channel bud

fallow mauve
alpine cove
#

isnt this used for dc bots?

potent spear
fallow mauve
#

at 8:43 he said "Docker is good since your libraries don’t magically downgrade" in this channel so it is right

#

bcs its a rpely to that

#

its related to discord bots bcs thats why i need it

potent spear
#

.

fallow mauve
#

ok fair point ig

#

how would i make a button copy a string to the users clipboard?

slate swan
#

Dear. why is it throwing an error? why is he a member and gives out a reaction for one text? how to fix? help me please

    @commands.has_role(982744620792426537)
    @commands.command(name = "бан", aliases = ["забанить", "ban"])
    async def command_clear(self, ctx, *, member: discord.Member, reason):

        try:
            await ctx.channel.purge(limit = 1)
            # await member.ban(reason=reason)

            memberName = member.name
            memberTag = member.discriminator
            author = ctx.author.name
            tag = ctx.author.discriminator

            embed = discord.Embed(
                title=(f"Был забанен {memberName}#{memberTag}")    ,
                color= 0xff0000
            )

            embed.set_footer(
                text="| Правительство SK",
                icon_url= ctx.guild.icon_url,
            )

            file1 = discord.File("./ImageS/user_card.png")

            embed.set_image(url='attachment://user_card.png')

            date = datetime.datetime.today()

            embed.add_field(name="Бан выдан:", value= (f"{author}#{tag}"), inline=True) 
            embed.add_field(name="Срок бана:", value="2 дня", inline=True) # по очереди потомучто в конце True
            embed.add_field(name='\u200b', value='\u200b', inline=False)
            embed.add_field(name="Причина Бана:", value=reason, inline=True) 
            embed.add_field(name="Дата выдачи:", value= date.strftime('%d-%m-%Y %H:%M:%S'), inline=True)

            await ctx.send(file=file1, embed=embed)
            os.remove("./ImageS/user_card.png")
        
        except discord.Forbidden:   return
shrewd apex
slate swan
#

Oh thanks

shrewd apex
#

👍

scarlet aurora
#
            message_redo.replace('e', '3').replace('a', '4')
            
            await message.channel.send(message_redo)``` Can someone tell me why this wont replace the characters in the message
#
    @commands.Cog.listener()
    async def on_message(self, message):

        if any(message.content.__contains__(baka) for baka in ["words"]):
            if  message.author.bot:
                return
            await message.delete()
            message_redo = message.content
            message_redo.replace('e', '3').replace('a', '4')
            
            await message.channel.send(message_redo)``` (Full code)
fallow mauve
#

how to test if a variable with a specific name exists

scarlet aurora
#

?

fallow mauve
#

so like if variable name exists:

???

#

idk how id do that

dull terrace
fallow mauve
dull terrace
#

just do if 'variablename' in locals()

slate swan
scarlet aurora
#

looks like u need to pip install a library

potent spear
slate swan
#
@Bot.command(name='join', help='Tells the bot to join the voice channel')
async def join(ctx):

    channel = ctx.message.author.voice.channel
    await channel.connect()
scarlet aurora
#

!pypi anime

unkempt canyonBOT
slate swan
#

If it is triggered, the !join command gives such an error.

slate swan
#

but i use Virtual Environments then I don't know which command to use.

potent spear
#

same thing... just run this in your venv...

scarlet aurora
potent spear
scarlet aurora
#

yes

#

but doesn't replace the message

#

like h3llo

slate swan
#

oh i think i figured it out. thnx man

dull terrace
#

Don't you need to assign it to a variable for replace @scarlet aurora

scarlet aurora
#

i did

#

message_redo

dull terrace
#

Variable = Variable.replace()

scarlet aurora
#

if some words r in the message

potent spear
fallow mauve
#

is it possible to make a music bot that plays songs from newgrounds.com?

scarlet aurora
#

thanks

potent spear
#

you have to redefine

potent spear
dull terrace
fallow mauve
slate swan
#

how do i get the id of a channel by mentioning it? example:
.channel #discord-bots
bot output:
ID: 343944376055103488

dull terrace
slate swan
#

I already got it by name, but I wanted to make by mention

dull terrace
#

If you're linking them it's different but playing them requires a deal and performance royalties I think

dull terrace
wraith lion
#

Heyy

#

How do I know, like how many members use my bot ( members of all the servers the bot is in )

scarlet aurora
#

how can I replace only the specialised word with the replacement words? ```py
@commands.Cog.listener()
async def on_message(self, message):

    if any(message.content.__contains__(baka) for baka in ["word", "WORD"]):
        if  message.author.bot:
            return

        await message.delete()

        messageredo = message.content
        message_redo = messageredo.replace('e', '3').replace('o', '0').replace('a', '4').replace(
            'i', '1').replace('E', '3').replace('O', '0').replace('A', '4').replace('I', '1')

        await message.channel.send(message.author.mention + " -> " + message_redo)```
slate swan
paper sluice
#

use a dict, u can do this

replacements = {'a': '1', 'b': '2'}
string = 'abc'
for key, value in replacements.items():
    string = string.replace(key, value)
slate swan
#

Dear. how to make a ban for 2 days? gives an error

    @commands.has_role(982744620792426537)
    @commands.command(name = "бан", aliases = ["забанить", "ban"])
    async def command_clear(self, ctx, member: discord.Member, *,reason, time: int):

        try:
            await ctx.channel.purge(limit = 1)
            # await member.ban(reason=reason)
            memberName = member.name
            memberTag = member.discriminator
            author = ctx.author.name
            tag = ctx.author.discriminator

            embed = discord.Embed(
                title=(f"Был забанен {memberName}#{memberTag}")    ,
                color= 0xff0000
            )

            embed.set_footer(
                text="| Правительство SK",
                icon_url= ctx.guild.icon_url,
            )

            file1 = discord.File("./ImageS/user_card.png")

            embed.set_image(url='attachment://user_card.png')

            date = datetime.datetime.today()

            embed.add_field(name="Бан выдан:", value= (f"{author}#{tag}"), inline=True) 
            embed.add_field(name="Срок бана:", value= time, inline=True) # по очереди потомучто в конце True
            embed.add_field(name='\u200b', value='\u200b', inline=False)
            embed.add_field(name="Причина Бана:", value=reason, inline=True) 
            embed.add_field(name="Дата выдачи:", value= date.strftime('%d-%m-%Y %H:%M:%S'), inline=True)

            await ctx.send(file=file1, embed=embed)
            os.remove("./ImageS/user_card.png")
        
        except discord.Forbidden:   return
scarlet aurora
#

@paper sluice smthing like this? ```py
@commands.Cog.listener()
async def on_message(self, message):

    if any(message.content.__contains__(baka) for baka in ["words"]):
        if  message.author.bot:
            return

        await message.delete()

        messageredo = message.content
        
        replacements = {'e': '3', 'a': '4', 'o': '0', 'i': '1'}

        for key, value in replacements.items():
            messageredo = messageredo.replace(key, value)

        await message.channel.send(message.author.mention + " --> " + messageredo)```
wraith lion
maiden fable
slate swan
slate swan
#

what you tryna do?

scarlet aurora
#

replace only the (baka) words in the message

wraith lion
slate swan
#

yes

scarlet aurora
#

@slate swan ?

wraith lion
maiden fable
slate swan
slate swan
slate swan
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

I dont know. I only need to

           embed.add_field(name="Срок бана:", value= time, inline=True) 

released 2 days

maiden fable
rare saddle
#

How to find the last message of a member in a channel?

maiden fable
#

channel.history(limit=1)

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
rare saddle
slate swan
maiden fable
slate swan
rare saddle
# maiden fable Wym

Well, find not just the last message in the chat, but from a specific user

maiden fable
#

move the time arg before the *

#

@slate swan I hate FastAPI 😔

slate swan
maiden fable
slate swan
#

can't you customise the logging yourself?

maiden fable
slate swan
#

or maybe you have been trying to

#

hmmm

maiden fable
#

Have u used the module before?

slate swan
slate swan
slate swan
maiden fable
slate swan
slate swan
maiden fable
#

That is what i need help with

maiden fable
slate swan
#

did you make a log config dict?

maiden fable
#

Tf is that

slate swan
maiden fable
#

idk anything about logging, sorry 😔

maiden fable
slate swan
unkempt canyonBOT
#

logging.config.dictConfig(config)```
Takes the logging configuration from a dictionary. The contents of this dictionary are described in [Configuration dictionary schema](https://docs.python.org/3/library/logging.config.html#logging-config-dictschema) below.

If an error is encountered during configuration, this function will raise a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError"), [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError"), [`AttributeError`](https://docs.python.org/3/library/exceptions.html#AttributeError "AttributeError") or [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError "ImportError") with a suitably descriptive message. The following is a (possibly incomplete) list of conditions which will raise an error...
maiden fable
#

sadly I don't have the JSON with me anymore since I forgot to commit to github 😅

slate swan
#

Is disnake slow in comparison to other libraries? Especially adding reactions and stuff?

maiden fable
#

no

slate swan
#

so basically FastAPI won't let you have ur own configs, weird

maiden fable
slate swan
slate swan
maiden fable
# slate swan show code owo

I wanna do smth like- Remove the sys.stdout and sys.stderr stream handlers from all the loggers in my code and instead make it so that they write logs to a log file

slate swan
#

Then maybe something is wrong with my upload speed. I'll check the program again later on 👍

maiden fable
# slate swan show code owo

This is my current code which outputs to both the file and the stdout:

root_logger = getLogger()
root_logger.addHandler(FileHandler(main_log_file))
root_logger.propagate = False
#
basicConfig(
        stream=file,
        force=True,
        level=DEBUG,
        style="{",
        format="{asctime} - {levelname}: {message}",
    )

This is inside an app.get() func, so there is a different log file for each request where file represents the log file

slate swan
#

did you try using thr filename kwarg in basicConfig?

maiden fable
#

yup, same thing

#

The issue is: It is writing to the log file

#

But it is also writing to console

tacit horizon
#

@slash.slash
@client.command
can i use both without making both separately

maiden fable
#

!d discord.ext.commands.hybrid_command

unkempt canyonBOT
#

@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").

A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").

The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.

Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.

New in version 2.0.
slate swan
#

I'll suggest to not use 3rd party libraries at all.

crisp drift
slate swan
#
global k
k = None

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

`discord.ext.commands.errors.ExtensionFailed: Extension 'commands.suggestion' raised an error: TypeError: Suggestion.__init__() missing 1 required positional argument: 'k'`
#

whats wrong?

maiden fable
slate swan
#

tried this?

maiden fable
#

Lemme try

maiden fable
crisp drift
#

logger.handlers[0] should return the stdout

maiden fable
#

Oh lemme print that

slate swan
maiden fable
#

istg tensorflow takes ages to load

maiden fable
crisp drift
#

Get a private channel so we dont talk here

slate swan
silk mauve
#

Are these the right permissions to activate the slash commands?

slate swan
#

at last

maiden fable
slate swan
#

its officially out.

maiden fable
#

I have that in some of my servers

paper sluice
#

github is fast, got pro in like 3 hrs damn i was expecting to way days just like i did for copilot xD

slate swan
paper sluice
#

try it 👀 👀

slate swan
#

nvm

maiden fable
paper sluice
#

they nais to kidz

maiden fable
#

Indeed lmao

shrewd apex
maiden fable
#

?

shrewd apex
#

i applied for student

maiden fable
#

Oh

paper sluice
shrewd apex
slate swan
#

it took 2 days for me get verified

shrewd apex
#

😌 i thought it was something wrong with mine

#

how do they even verify btw?

#

they hack into school db?😎

slate swan
unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

shrewd apex
#

🥲 sorry just a jk

maiden fable
#

No verifications

shrewd apex
#

oh no wonder it takes time

#

the guy responsible for my Id is on a lunch break probablypithink

cloud dawn
paper sluice
maiden fable
shrewd apex
#

mine does ig...

cloud dawn
#

I got verified in 1 second because of that.

shrewd apex
#

welp it doesn't

slate swan
#

you guys sure can move to an ot channel, right?

maiden fable
#

Talk ended

regal pulsar
#

hello

maiden fable
#

Hi

tepid sundial
#

!d await connect

unkempt canyonBOT
tepid sundial
#

help me for joine voice my bot

#

im in persian

heady sluice
#

!d discord.VoiceChannel.connect

unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
tepid sundial
#

TNX ❤

slate swan
#

Dear, please tell me how to display days instead of seconds

    @commands.has_role(982744620792426537)
    @commands.command(name = "бан", aliases = ["забанить", "ban"])
    async def command_ban(self, ctx, member: discord.Member, reason, *, time: int):

        try:
            await ctx.channel.purge(limit = 1)
            # await member.ban(reason=reason)

            memberName = member.name
            memberTag = member.discriminator
            author = ctx.author.name
            tag = ctx.author.discriminator

            embed = discord.Embed(
                title=(f"Был забанен {memberName}#{memberTag}")    ,
                color= 0xff0000
            )

            embed.set_footer(
                text="| Правительство SK",
                icon_url= ctx.guild.icon_url,
            )

            file1 = discord.File("./ImageS/user_card.png")

            embed.set_image(url='attachment://user_card.png')

            date = datetime.datetime.today()

            embed.add_field(name="Бан выдан:", value= (f"{author}#{tag}"), inline=True) 
            embed.add_field(name="Срок бана:", value= time, inline=True) # по очереди потомучто в конце True
            embed.add_field(name='\u200b', value='\u200b', inline=False)
            embed.add_field(name="Причина Бана:", value=reason, inline=True) 
            embed.add_field(name="Дата выдачи:", value= date.strftime('%d-%m-%Y %H:%M:%S'), inline=True)

            await ctx.send(file=file1, embed=embed)
            os.remove("./ImageS/user_card.png")
        
        except discord.Forbidden:   return
maiden fable
#

U gotta make a TimeConverter, I told u

left idol
#

in pycord after i use a slash command and interact with a button, there is a leftover reply that says the application did not respond but i see that everything i wanted to happen after clicking the button worked. is this because of interaction.defer()? how would i fix this

maiden fable
slate swan
maiden fable
unkempt canyonBOT
#

class discord.ext.commands.Converter(*args, **kwargs)```
The base class of custom converters that require the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") to be passed to be useful.

This allows you to implement converters that function similar to the special cased `discord` classes.

Classes that derive from this should override the [`convert()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Converter.convert "discord.ext.commands.Converter.convert") method to do its conversion logic. This method must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
heady sluice
#

you did it right

#

what's the question

#

make an embed and send it

#

pretty sure you've made plenty of embeds already

#

and in the if you can set the embed title

#

or make the embed in the if

slate swan
#

Copy paste

heady sluice
#

this is like asking how to do square roots in 12th grade

shrewd apex
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
dull terrace
#

hyperlinks allowed in discord footers?

slate swan
dull terrace
#

poop

sick birch
slate swan
#

looli f

weak moat
#

How do I specify a user limit when creating a channel?

spring flax
#

What do you mean

weak moat
#

Well, I'm creating a voice channel with the help of a command, how can I make it so that when using a command in this voice channel, a connection limit for 1 person is made

regal pulsar
#

guys

#

where exactly in the embed are hyperlinks allowed

sick birch
regal pulsar
#

i know the title allows it

vocal plover
#

field bodies and the description

regal pulsar
#

but where else

regal pulsar
slate swan
# maiden fable

I figured it out, thanks. although this thing is very difficult for me, I did it differently. via if

vocal plover
#

the title doesnt allow it, but may have a url provided as a separate parameter iirc

sick birch
slate swan
maiden fable
#

That is the way most people who ain't familiar with converters go for

slate swan
#

Well, I downloaded python a week ago.

slate swan
#

I decided to study python because js seemed difficult

sick birch
#

They're about on the same level of difficulty

regal pulsar
#

its an opinion but i think python is easier

#

not to mention way cleaner

maiden fable
regal pulsar
#

lol

sick birch
maiden fable
#

Loll

#

I had a meme somewhere regarding some weird JS stuff

#

smth like 0 === [] is true but the vice versa ain't

sick birch
#

'5' == [[5]]

maiden fable
#

Brb lemme bleach my eyes

#

don't tell me that's true

sick birch
maiden fable
#

Good thing I don't code in JS

sick birch
#

yeah luckily though if you use == other JS devs are going to give you the death stare

#

it's almost a sin to use == nowadays

maiden fable
#

Saw it

spring flax
#

I have this multi-line f string in my embed description```py
"""
{FIVE} Excellent {"".join(bar_form(five_stars))}

{FOUR} Very Good {"".join(bar_form(four_stars))}

{THREE} Good {"".join(bar_form(three_stars))}

{TWO} Fair {"".join(bar_form(two_stars))}

{ONE} Poor {"".join(bar_form(one_stars))}
"""

#

the {"".join(bar_form(five_stars))} is a list of emojis.
I'm trying to make that list of emojis appear at the same indent as each other list down. but the above code gives

#

what do I change?

sick birch
#

You need special characters that look like spaces but aren't

spring flax
#

do you have the unicode?

sick birch
spring flax
#

i also want it to be more closer to the words, if possible

sick birch
#

The regular whitespaces have to be replaced as well

#

The ones after "good" "fair" and "poor"

vocal plover
#

I think in this case you should probably try to find a workaround, semantic whitespace without a monospace font is always gonna look funky on some device, perhaps put the stars bar between the number and the text

sick birch
#

Or dots, like a table of contents

spring flax
#

what do you mean dots?

sick birch
#

Like
5️⃣ Excellent ................................................................ ⬛⬛⬛⬛⬛⬛⬛⬛⬛

white citrus
#

My bot is not online. I use heroku

regal pulsar
#

thats vague

#

heroku isnt meant for bot hosting

rocky trench
#

it cant find the interaction

#

I assume you tried to react to a message the bot sent before a restart

steel slate
#
role = await self.client.get_role(9042165867449938699355402)
                await member.add_roles(role)
#

'Bot' object has no attribute 'get_role'

atomic path
#

you can only get a role from a guild

#

persistent views?

placid skiff
atomic path
#

sure you can use utils.get etc

regal pulsar
unkempt canyonBOT
steel slate
steel slate
atomic path
# steel slate so i forgot guild?

no, just bot does not have a get_role method
you cannot do bot.get_role you get do guild.get_role though
so to get guild you can do bot.get_guild(id) OR if this is in a place where you can access the context you can do ctx.guild.get_role /message.guild.get_role or whereever this is located

atomic path
# steel slate this is discord.py

I mean it overall works the same disnake and others are forks of dpy, meaning the majority of their codebase is the same as dpy
just newer features differ and branch out

thorny flint
#

So this is regarding the autocomplete feature for slash commands..
Is there a way to just fetch once from a database? like when the user starts using the command

async def autocomplete_username(self, ctx: CommandContext, user_input: str = ""):
        choices  = []
        accounts = await api_request(method="get", request_url=get_accounts, account=ctx.author.id)

        for account in accounts['accounts']:
            if user_input.lower() in account['username'].lower():
                choices.append(Choice(name=f"{account['username']}", value=f"{account['username']}"))
        log.debug(f"Choices for autocompletion : {choices}")
        await ctx.populate(choices)

So that it only run api_request() once, when the user start typing the command

old nest
#

im trying to make specific arguments of a command require specific roles how would i do that?

for example

!credits add * Only for admins
!credits use * Only for members

potent spear
#

where you use command checks for every different group command

steep drift
#
slate swan
#

hm the first thing that I'll suggest it to not use json

#

you may use some local db like sqlite3 instead, which is actually meant for data storage purpose

potent spear
#

^^ this will be your main focus, start by using an actual DB, with an async wrapper
like for example
aiosqlite is the async wrapper of sqlite

frozen patio
#

Ok so I am trying to import a file from another folder into my cog file

#

But it gives me this error

slate swan
#

is tools a top level folder?

frozen patio
#

The folder I am importing into is the Cogs

#

Then the Tools Folder

slate swan
#

oh yes you are, thats the issue
dw that won't raise an error when you run the main file CL_KokoSip

#

just a sidenote: use underscore_naming instead of camelCase in python for variable and file namings
for classes it would be PascalCase

sick birch
#

What command are you running to start your bot?

#

That's why

#

you have to run python3 main.py i believe

#

And what happens?

#

Does it do that instantly?

#

Or is there a delay

#

maybe try py main.py?

#

!paste Ah okay, can you paste the entirety of main.py in here?

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.

sick birch
#

No client.run()?

#

🤔 strange it should at least say it's ready

#

Can you try printing something before you do the client = commands.Bot(...) stuff?

median widget
#

Am I able to make a bot repeat a command every hour?

sick birch
frozen patio
sick birch
#

Oh something's really wrong then

frozen patio
#

Or the bot's prefix can't be found

sick birch
#

Can you move the print statement to the first line?

#

It should be at the very top

sick birch
#

oh my, that's not right at all

slate swan
#

your problem is with relative imports

sick birch
#

I doubt it's nextcord

#

Since it can't even run a print statement as the first line

#

Just for testing, can you remove everything else and only have the print statement? so your entire file should just be one line with the print statement

#

that way we can narrow it down to a nexcord issue or python issue

#

It wouldn't even run that file with a print?

#

Can you try command prompt?

#

Use cd to navigate to the right folder

slate swan
#

vscode has a python extension for running code, try using it to run the code maybe?

boreal ravine
#

@slate swan Are you sure you're running the file your editing?

unique spruce
#

Where can I show off my projects

boreal ravine
#

Did you save your file?

boreal ravine
unique spruce
#

Games

boreal ravine
#

I think

#

I don't really know

sick birch
#

What does the prompt say?

#

I mean, what does it say to the left of your cursor? The stuff before the >

median widget
#

am i able to make bots on mac?

#

or do i need to use windows

sick birch
#

That should tell you what your cwd is

#

You can code on any computer really

#

I can code just fine on my macbook pro

#

Though usually I'm on linux on my desktop

median widget
#

okay, do u know how i can access this on mac?

#

its for the bot

sick birch
#

Wdym access it?

median widget
#

idk how to get to it

slate swan
#

its the terminal~

median widget
#

cause the tutorial did it on windows

#

i cant get it on mac

sick birch
#

Node should have a specialized mac download

median widget
#

i downloaded it

sick birch
#

Can you show me what it downloaded?

#

It shouldn't be an exe

median widget
#

okay

#

hold on

sick birch
#

Can you try using command prompt?

median widget
#

thats where

boreal ravine
#

that's node

sick birch
#

🤔

median widget
#

yeah

sick birch
#

Did you install the macOS installer or macOS binary?

boreal ravine
slate swan
#

😩 just use brew to install node&npm

sick birch
#

brew ⁉️

slate swan
median widget
#

i clicked on that and it installed it without saying which one

boreal ravine
#

Why are you even asking about node in a python server?

sick birch
#

And did you double click the .pkg?

median widget
slate swan
#

well this channel is meant specifically for discord bots with python help

median widget
#

then where should i go to get help

slate swan
median widget
#

okay

#

thanks for the help

proud anvil
#

hey can any1 help me with a problem I'm tryna figure out with my crypto bot

#

so basically I have a database off a bunch of crypto currencys and there price [id], [current-price]

#

and I want to make it so that when someone does $crypto-name it responds with the price

boreal ravine
#

Doesn't sound like a problem to me?

proud anvil
#

but right now it just responds when someone writes the cryptos name because I check the message by saying if message.content.lower() in db.keys():

proud anvil
#

and I don't understand how to change it so it responds when it starts with a $ while fetching it

proud anvil
#

‘‘‘if message.content.lower() in db.keys():
await message.channel.send(f'The current price of {message.content.lower()} is ${getCryptoPrices(message.content.lower())}')’’’

boreal ravine
#
bot = Bot(command_prefix='$')

@bot.command(name='crypto-name')
async def crypto_name(ctx, name, ...) -> ...:
    ... # get the cc and get its price
lyric apex
#

How to ignore the commands when the command usage is exceeded like the command is *bot but it replies when someone writes after it

boreal ravine
#

!d discord.ext.commands.Bot import it.. or import commands from discord.ext

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), This class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
slate swan
#

it will raise a commands.TooManyArguments error if user provides extra arguments

lyric apex
#

It will be too long i have more than 280 cmdsSad_Cat

slate swan
# lyric apex Everywhere?

im not sure if there's a shortcut to do it everywhere automatcially, but you can just
you can just ctrl+f command( and replace it with command(ignore_extra=False,

lyric apex
#

This would work on ready func?

steep drift
slate swan
lyric apex
#

That worked

slate swan
#

gg

chilly flame
#

U ugly

boreal ravine
slate swan
#

its just replit being replit

#

i would recreate the pyproject.toml by my own but you should do that only when you are aware how poetry works

karmic marsh
#

Hi

slate swan
#

create a new repl then :)

#

this might be an issue with replit's outdated python version too.

karmic marsh
#

I have basically no clue what I'm doing... I'd like to code a discord bot and I have experience in c#, c++, python, and a little bit in js and java.

I've made one discord bot in replit following a tutorial but I still don't know what I'm doing and I'd like to build a bot to run locally on my own server. Are there any good resources out there that I should start by checking out?

slate swan
karmic marsh
#

uhh... more or less?

#

I'm less experienced with python than I am with c# or c++

slate swan
#

!resources you can actually look into these first, since already have a hold on cpp,i believe you are already aware of how objects works?

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

karmic marsh
#

yeah, I think so

maiden fable
#

Code

slate swan
#

googlesearch isnt asynchronous...is it?

#

!pip google

unkempt canyonBOT
spring flax
#
            e.description = f"""
            Current Community Rating: 
            {overall_stars}
            {avg_rating} out of 5 stars
            {sum(single_reaction.count -1 for single_reaction in all_reactions)} ratings
                    
            5 stars
            {"".join(bar_form(five_stars))}
            
            4 stars
            {"".join(bar_form(four_stars))}
            
            3 stars
            {"".join(bar_form(three_stars))}
            
            2 stars
            {"".join(bar_form(two_stars))}
            
            1 star
            {"".join(bar_form(one_stars))}
            
            """
            await message.edit(embed=e)

the output of this on pc is like this

#

but on mobile it's like this

#

why the indent on mobile?

stone beacon
#

Cuz

#

Screen smol

#

And discord mobile is weird sometimes. It's probably because of screen size why that happens udk

maiden fable
#

Indeed

final pumice
#

does discord have a bar?

maiden fable
#

It will look different on an iPad/Tablet

maiden fable
final pumice
spring flax
#

so nothing I can do?

final pumice
#

woops

stone beacon
final pumice
#

i mean @spring flax

stone beacon
#

Ahh

visual island
#

That's an emoji

spring flax
#

i made it with emojis

final pumice
#

oh

#

thats smart

paper sluice
spring flax
#

sure it'll work right?

paper sluice
#

!e

import textwrap
a = """
    hello
    world
    """
b = textwrap.dedent(a)
print(a)
print(b)
visual island
#

No that's just discord mobile issue

unkempt canyonBOT
#

@paper sluice :white_check_mark: Your eval job has completed with return code 0.

001 | 
002 |     hello
003 |     world
004 |     
005 | 
006 | hello
007 | world
stone beacon
#

Doubt that would affect how it's rendered on mobile as embeds have a fixed max width

spring flax
#

i'll just fwiw

paper sluice
spring flax
#

oh perfect thank you Ryuga that worked

slate swan
#

Is it possible to have slash commands which are only visible to a few people?

spring flax
#

Yes

#

With the discord slash command permission found in server settings > intergrations

slate swan
shrewd apex
#

@command_name.error

slate swan
#

Oh okay, I thought it only worked with the prefixed commands only. Thanks Asher :)

left idol
#

with pycord

rnames = []
for role in player.roles:
    rnames.append(role.name)

trole = discord.utils.get(ctx.guild.roles, name=team)
if rnames in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
    await player.remove_roles(['Tokyo Fart Sniffers', 'Baltimore Bughas'])
    await player.add_roles(trole)
elif rnames not in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
    await player.add_roles(trole)

is this format for removing roles in list wrong? i tried my command but it doesn't remove the users roles

slate swan
#

remove_roles takes a discord.Role object, not a list

left idol
#

ah so i'd have to put it in a for loop then

slate swan
#

no. it would be still wrong

#

cause it needs to be a Role, not a string

visual island
#

You can unpack the list of Role objects to add_roles/remove_roles

slate swan
#

Role``*Role*Role

#

Ahh.

#

Should i make ghost ping logs or message delete logs are enough?? :?

odd mango
#

hey, when i do from discord.ext import menus, it gives me this error

#

i tried pip install git+https://github.com/Rapptz/discord-ext-menus.git, but it had no effect

#

what do i do

#

how do i install git+https://github.com/Rapptz/discord-ext-menus.git in dpy.ext location

GitHub

Contribute to Rapptz/discord-ext-menus development by creating an account on GitHub.

paper sluice
#

-U tag means upgrade so ur modifying the already installed one

cloud dawn
#

What version of dpy are you running? 1.7.3 or 2.0?

odd mango
#

2.0

cloud dawn
#

Lemme search around.

odd mango
paper sluice
#

ya

#

a venv is like another installation of python, so u have to install it there as well

cloud dawn
odd mango
#

thanks a lot you guys

cloud dawn
#

As for pypi packages it has a build in search in there too.

short silo
#

i am using interaction.send_modal

but i get an error that modal has no attribute to dict.

Any idea on how to fix it ?

magic pond
#

how to find if a member has any badge in their profile ?

paper sluice
#

!d discord.User.public_flags

unkempt canyonBOT
toxic crypt
#

@unkempt canyon u suck >:)

unkempt canyonBOT
#
Bad argument

Could not convert "user_or_message" into Member, User, or Message.
Message "suck" not found.

#
Command Help

!user [user_or_message]
Can also use: member_info, member, u, user_info

Returns info about a user.

toxic crypt
toxic crypt
spring flax
#

what

slate swan
placid skiff
#

Ashley today i will start learning hikari

cloud dawn
slate swan
cloud dawn
slate swan
#

its easy though good luck

slate swan
placid skiff
#

It's weirdness

slate swan
#

CommandTree

cloud dawn
slate swan
#

what I would expect something from a third party lib

#

I mean, who would have thought to have shat that much

cloud dawn
#

You got a point tough the commandtree is just very bad atm.

slate swan
#

xD, and the manual sync is a big headache

short silo
#
Ignoring exception in command bug_report:
Traceback (most recent call last):
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 126, in wrapped
    ret = await coro(arg)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 856, in _invoke
    await self.callback(ctx, **kwargs)
  File "e:\Python PRojects\Top War Bot\Top war bot\Cogs\Bug_Report.py", line 34, in bug_report
    await ctx.send_modal(modal=modal)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 899, in send_modal
    payload = modal.to_dict()
AttributeError: 'Modal' object has no attribute 'to_dict'

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

Traceback (most recent call last):
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 993, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 357, in invoke
    await injected(ctx)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 134, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Modal' object has no attribute 'to_dict'

slate swan
#

if they were worried about uniqueness, they sure did a good job of having their users have to do more work

cloud dawn
short silo
#
CODE:

modal = Modal(
        custom_id="Bug Report",
        title="Bug Report",
        components=[
            TextInput(
                style=TextStyleType.SHORT,
                custom_id="What kind of Bug",
                label="What kind of bug ?",
                placeholder="Purchase Related, In-game Related etc.",
                required=True
            ),
            TextInput(
                style=TextStyleType.SHORT,
                custom_id="Server Related ?",
                label="Please specify which server in case of a server-specific bug.",
                placeholder="Leave blank if it is not.",
                required=False
            )

        ]
    )
    await ctx.send_modal(modal)
maiden fable
#

What lib

slate swan
maiden fable
#

@short silo u on the latest version?

cloud dawn
maiden fable
#

Idk try seeing if u r doing the same thing

slate swan
#

gonna annoy people in the dpy server now

cloud dawn
#

Yeah I suggest using this method, looks better as well.

boreal ravine
slate swan
#

hm yeah figured that out but still

fiery sphinx
#

hello

cloud dawn
#

👋

fiery sphinx
#

can bot use commands other bots ?

#
await ctx.send("!help")

and other bots get respond?

cloud dawn
fiery sphinx
cloud dawn
#

@slate swan

#

lmfao

#

i saw that

paper sluice
#

sad ashley noises

slate swan
cloud dawn
#

assumes gender

slate swan
#

no

#

;-;

slate swan
#

and I saw that, you didn't have to delete it, I wasn't gonna bite you or anything

#

😐

slate swan
#

sorry for what, told you its okay

shrewd apex
placid skiff
slate swan
#

💀 msg deleted

paper sluice
#

!ot 💀

regal pulsar
unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
maiden fable
placid skiff
#

This channel is for telling people to learn python for half of the time and the other half for us talkin' about people who want to code a bot in d.py without knowing python

ornate tundra
placid skiff
slate swan
#

!d discord.Member.timeout

unkempt canyonBOT
#

await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
slate swan
#

ye that

placid skiff
#

Oh wait does he means timeout a member or command cooldown? xD

short silo
ornate tundra
#

or is it even new now

placid skiff
#

well now it is pretty old

#

thing get old really fast

#

but yeah it's the newest member moderation option

odd mango
#

how do i disable buttons on timeout

ornate tundra
#

imma just try to do random stuff and hope it works

#

do i have to import anything

slate swan
#

u can change the timedelta time according to you

ornate tundra
#

mute and timeout is basically same right?

slate swan
#

no

odd mango
#

timeout is like a temp ban

#

you stay in the server but cant see shyt

ornate tundra
#

i thought timeout came out to replace mute

odd mango
#

naww

ornate tundra
slate swan
#

in mute bot gives a role to the person which doesnt have permissions to msg or not see the channel
and in timout
the discord gives u a feature that u can use instead of mute

odd mango
#

anyone knows how can i disable buttons :/

paper sluice
odd mango
#

after timeout

odd mango
#

yeah

paper sluice
odd mango
#
class MyMenuPages(ui.View, menus.MenuPages):
    def __init__(self, source, *, delete_message_after=False):
        super().__init__(timeout=60)
        self._source = source
        self.current_page = 0
        self.ctx = None
        self.message = None
        self.delete_message_after = delete_message_after```
placid skiff
#

!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.
paper sluice
odd mango
#

here my menu timeout is 60, when clicked after 60 secs, it says interaction failed

#

ohhhh thanks a lot

placid skiff
#

uhm it should be an async def lol

paper sluice
#

ya

odd mango
#

did that yeah

#

i'll go try

odd mango
#

not working @paper sluice@shrewd apex

#

oh want, where do i await it

#

ok nvm got it

#

i will go try rq

lyric apex
#

How to add multiple emojis mentioned?

latent yarrow
#

@hot plaza

hot plaza
#

?

latent yarrow
#

@hot plaza hi i am learning python

#

could u help me in make a discord bot mute command

lyric apex
#

Show the code brov_cat

latent yarrow
#

here the mute command

lyric apex
#

Copy paste 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.

hot plaza
latent yarrow
#

oh k

#

wait

#
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member):
    guild = ctx.guild
    Muted = discord.utils.get(ctx.guild.roles, name="Muted")
    perms = discord.Permissions(send_messages=False,connect=False,read_message_history=True)
    if Muted not in guild.roles:
        await guild.create_role(name="Muted")
        await member.add_roles(Muted)
        em1=discord.Embed(title="Sucsessfully Muted",description=f"{member.mention} Has been Breaking the Rules",colour=discord.Colour.random())
        await ctx.send(embed=em1)```
lyric apex
hot plaza
lyric apex
#

Alr

latent yarrow
hot plaza
#

@latent yarrow you might benefit from following a tutorial on youtube

latent yarrow
#

though i use youtube still i dont understand

#

it's giving me the error

hot plaza
#

whats the error then

latent yarrow
#

like this: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'

lyric apex
#

Full traceback?

latent yarrow
#

@hot plaza is this clear

hot plaza
heavy folio
#

Don't recommend that

hot plaza
latent yarrow
#

it is

heavy folio
#

Nah

#

Following the docs best

hot plaza
hot plaza
heavy folio
#

Reading the docs is a key step to being a developer

placid skiff
#

better, it's the first

heavy folio
#

Indeed

placid skiff
#

the second one is understanding users docs

odd mango
#

where and how do i await

    async def on_timeout(self):
        for button in self.children:
            button.disabled = True```
heavy folio
#

You edit the message's view

odd mango
#

i want my buttons to be disabled on timeout

odd mango
heavy folio
#

I believe you have a message attribute in your view class

odd mango
#

view.edit?

heavy folio
#

!d discord.Message.edit

unkempt canyonBOT
#

await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
odd mango
#

ooh

#

okay okay got it

#

so in this case

#

i do view=on_timeout?

latent yarrow
#

@hot plaza

heavy folio
#

Nope

#

view=self

latent yarrow
#
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'```
hot plaza
heavy folio
#

Then learn python first, that'll definitely benifit them
Discord.py and similar libraries aren't beginner friendly.

lyric apex
#

They now prefer learning by mistakes*

odd mango
# heavy folio view=self

look i do it this way

menu = MyMenuPages(formatter, delete_message_after=True)
await menu.start(self.context)```
#

i start start the menu this way

heavy folio
#

Hmm

#

Can you show the menu.start function

odd mango
#

yea holup

#
    async def start(self, ctx, *, channel=None, wait=False):
        await self._source._prepare_once()
        self.ctx = ctx
        self.message = await self.send_initial_message(ctx, ctx.channel)```
heavy folio
#

Yeah you can access the message using self.message

#

In on_timeout, await self.message.edit(view=self)

odd mango
#

cool! ty

shrewd apex
#

any reason this dosent work?

    view = View(timeout=5)
    async def disabled(self):
        for button in self.children:
            button.disabled = True
        await self.message.edit(view=self)

    view.on_timeout = disabled
maiden fable
#

Weird

shrewd apex
#

i tried the same thing in a button callback and it worked

maiden fable
#

Should have worked

latent yarrow
#

@hot plaza : Traceback (most recent call last): File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'

#

this is my error

shrewd apex
#

is it due to self.message.edit

#

i havent sublassed calling in function as of now

latent yarrow
#

@hot plaza help pls

#

u r a genius in this na??

#

so help

latent yarrow
#

wait

#
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member):
    guild = ctx.guild
    Muted = discord.utils.get(ctx.guild.roles, name="Muted")
    perms = discord.Permissions(send_messages=False,connect=False,read_message_history=True)
    if Muted not in guild.roles:
        await guild.create_role(name="Muted")
        await member.add_roles(Muted)
        em1=discord.Embed(title="Sucsessfully Muted",description=f"{member.mention} Has been Breaking the Rules",colour=discord.Colour.random())
        await ctx.send(embed=em1)```
#

here is it

#

@alpine cove

#

the code's here

#

@hot plaza

alpine cove
#

looking but im on phone rn so it doesnt format

#

havent seen a .id call yet

slate swan
#

Same.

alpine cove
#

commands.has_permission may be the problem

#

would make sense if the method calls .id

#

od discord.utils.get

latent yarrow
#

ok i will try

slate swan
#

Wever, do you know how to change the "This interaction has failed" to something else? Kinda like an error handler for slash command with an ephemeral but with red coloured warning.

alpine cove
#

isnt there on slash command errir

#

*error

slate swan
#

Will @unborn owl_command_name.error() work?

#

But I want the red.

shrewd apex
maiden fable
#

Nice I almost reported this msg of yours

paper sluice
#

?

maiden fable
#

Discord Mobile being a bitch

paper sluice
#

ouf

vale wing
#

Yes

shrewd apex
#
    view = View(timeout=5)
    async def disable(self):
        for item in self.children: item.disabled = True
        await self.message.edit(view=self)
    view.on_timeout = disable
#

thats still ok i can manage even if it dosent but the disable function dosent run at all

vale wing
#

View doesn't have message attribute dude

shrewd apex
#

i added a print under the disable function and got nothing

shrewd apex
vale wing
#

How can you tell

latent yarrow
#

@alpine covenot working

shrewd apex
#

i added print nothing printed heck i even did self.somegarbledshit and still no error

vale wing
#

Do you send the view actually

#

Timeout counts since the message with view was sent iirc

shrewd apex
#

yeah i did

vale wing
#

Does it have any components

shrewd apex
#

two buttons

vale wing
#

And the buttons display correctly right?

shrewd apex
#

yes

vale wing
#

Try increasing the timeout to like 15

#

subclass the view for god's sake

shrewd apex
#

buttons work everything works except the on timeout even when i disable the view in the button callback it works

paper sluice
#

just delete the message on timeout, why disable buttons

vale wing
#

His function doesn't even get called for some reason

shrewd apex
#

yeah but the problem is it dosent get called at all

paper sluice
vale wing
#

Subclass the view and try to define it there