#discord-bots

1 messages · Page 973 of 1

sick birch
#

Say you're using requests within an async function

#
async def make_request(...):
  requests.get(...)
pliant gulch
#

Some people are under the misconception that making it a coroutine function would make it suddenly not blocking

sick birch
#

Still blocks

slate swan
#

ah you guys mean that

#

sorry i couldnt really understand before

sick birch
#

Which is... distasteful

pliant gulch
#

If your gonna do async, go all out

#

It’s pretty important to have an understanding, otherwise it would be like black magic

sick birch
#

Yeah, that only hinders your learning

boreal ravine
#

yes

boreal ravine
high nexus
#

yo guys how do I check if a member exists in a guild by uid

boreal ravine
pliant gulch
#

This is super in-efficient

#

Just check get_member

#

If Guild.get_member returns None the member doesn’t exist

#

Else it would return the member instance

sick birch
#

Isn't get_member O(1)

#

Since it's only fetching from cache

pliant gulch
#

Yes it’s a hash lookup

sick birch
#

Makes sense

high nexus
#

how do I create guild object I forgot lol

sick birch
#

if id in [m.id for m in guild.members] I'm guessing is O(n^2)?

#

Either that or 2n

sick birch
pliant gulch
#

List comp would be O(n) and contains would also be O(n) so O(2n) yea

sick birch
#

The library provides them for you

high nexus
#

oh ok

high nexus
#

so I do get_member ?

sick birch
#

Yes

high nexus
#

member object right?

#

or uid?

sick birch
#

Optional member object, yes

high nexus
#

ok thanks

sick birch
#

get_member() -> Optional[discord.Member]

high nexus
#

what do I have to import fir guild

sick birch
#

Hm?

high nexus
#

undefined

sick birch
#

I'm not following

high nexus
sick birch
#

It's a method of discord.Guild object, so it's guild.get_member()

boreal ravine
pliant gulch
#

hole in cup, still holds water but still leaks

sick birch
lament mesa
bleak karma
#

help?

  @commands.group()
  async def message(self, ctx):
    await ctx.send("do !message create {text}")

  @message.command()
  async def create(self, ctx, *, text=None):
    if text == None:
      await ctx.send("text is required")
    else:
      await ctx.send(f"{text}")

it sends both do !message create {text} and text is required if i do !message create but i want it to send only the text is required message when doing !message create and text is required if doing !message only idk if this makes sense

sick birch
sick birch
#

Anytime

slate swan
#

nah

blissful sparrow
#

this error doing my head in
https://caught-lackin-in-8k-by-cyberghost.cf/x8Ra9m2Q

def get_prefix(ctx:commands.Context):
    conn = sqlite3.connect('./sql/ghost_bot.db')
    c = conn.cursor()
    c.execute('CREATE TABLE IF NOT EXISTS ghost_bot(guild_id TEXT,prefix TEXT)')
    c.execute(f'SELECT ghost_bot WHERE guild_id = {ctx.guild.id}')
    result = c.fetchone()

    if result:
        prefix = str(result[0])

    if not result:
      prefix = '.'

    conn.commit()
    c.close()
    conn.close()

    return prefix
You wasted 84.22 KB of space!

Caught lacking on Apr 13, 2022, 2:54 AM

slate swan
#

like*

blissful sparrow
#

I'm passing it where the prefix for the bot would be defined

slate swan
blissful sparrow
#

I dont understand where its getting the second param from though wob

#

And that error shows every few seconds rendering the bot basically useless lol

slate swan
#

i mean.. the place where you've used that function

jovial pilot
#

What should i use to detect if a message is sent in any channel of a discord server

#

But from a specific server id

blissful sparrow
slate swan
slate swan
blissful sparrow
#

at this point anything is worth a try haHAA

slate swan
#

at least nothing wrong with trying ig :'/

blissful sparrow
#

same error but it spits out a lot faster now

#

boutta get my laptop's cpu railed

slate swan
#

lmfaoo

slate swan
blissful sparrow
#
  File "C:\Python310\lib\site-packages\discord\client.py", line 375, in _run_event
    await coro(*args, **kwargs)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1279, in on_message
    await self.process_commands(message)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1274, in process_commands
    ctx = await self.get_context(message)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1173, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1089, in get_prefix
    ret = await discord.utils.maybe_coroutine(prefix, self, message)  # type: ignore
  File "C:\Python310\lib\site-packages\discord\utils.py", line 617, in maybe_coroutine
    value = f(*args, **kwargs)
TypeError: get_prefix() takes 1 positional argument but 2 were given```
#

what if it dont like the func name

slate swan
#

i'm thinking the same

#

lol

blissful sparrow
#

File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1089, in get_prefix
ret = await discord.utils.maybe_coroutine(prefix, self, message) # type: ignore

#

specifically cos that

slate swan
#
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1173, in get_context
    prefix = await self.get_prefix(message)
``` i'm thinking cuz of this lmao
blissful sparrow
#

nope name seems fine

#

cos i still get error when tryna execute any cmd

#

mayn I still gotta add a function to whitelist guilds so I can make a cmd for it kms

#

i cant get past this prefix bs

slate swan
#

🤔 ** ** || i'm feeling brainless btw, lmao||

blissful sparrow
#

lmfao same

#

!paste

#

this is all the errors its spat after restart

quick gust
quick gust
blissful sparrow
quick gust
#

firstly ure still supplying it in your bot constructor, and secondly its not really needed

#
async def get_prefix(bot, message):
    ...
blissful sparrow
quick gust
green bluff
#

how to set permissions in a category again?

blissful sparrow
#

I believe that worked but now its saying theres no column called prefix when in the line above its literally ```py
c.execute('CREATE TABLE IF NOT EXISTS ghost_bot(guild_id TEXT,prefix TEXT)')

boreal ravine
blissful sparrow
#

Yes

#

I sent a ss earlier

boreal ravine
#

does the column exist?

blissful sparrow
blissful sparrow
#
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\client.py", line 375, in _run_event
    await coro(*args, **kwargs)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1279, in on_message
    await self.process_commands(message)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1274, in process_commands
    ctx = await self.get_context(message)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1173, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1089, in get_prefix
    ret = await discord.utils.maybe_coroutine(prefix, self, message)  # type: ignore
  File "C:\Python310\lib\site-packages\discord\utils.py", line 619, in maybe_coroutine
    return await value
  File "c:\Users\Admin\Desktop\Ghost-Utilities-Bot\bot.py", line 17, in get_prefix
    c.execute(f'SELECT prefix WHERE guild_id = {message.guild.id}')
sqlite3.OperationalError: no such column: prefix
#

boutta yeet this laptop out the window XD

quick gust
boreal ravine
#

oh yeah

boreal ravine
blissful sparrow
quick gust
#

its safe since its only the guild id
but yes its bad practice

boreal ravine
#
c.execute('select prefix from ghost_bot where guild_id=?', (message.guild.id,))
blissful sparrow
#

Omg im a genius I thought it was that bigbrain

#

XD

#

I mean thanks

#
Traceback (most recent call last):
  File "C:\Python310\lib\site-packages\discord\client.py", line 375, in _run_event
    await coro(*args, **kwargs)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1279, in on_message
    await self.process_commands(message)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1274, in process_commands
    ctx = await self.get_context(message)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1173, in get_context
    prefix = await self.get_prefix(message)
  File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1089, in get_prefix
    ret = await discord.utils.maybe_coroutine(prefix, self, message)  # type: ignore
  File "C:\Python310\lib\site-packages\discord\utils.py", line 619, in maybe_coroutine
    return await value
  File "c:\Users\Admin\Desktop\Ghost-Utilities-Bot\bot.py", line 17, in get_prefix
    c.execute('SELECT prefix FROM ghost_bot WHERE guild_id = ?', (message.guild.id))
ValueError: parameters are of unsupported type
#

yes, I love errors

green bluff
boreal ravine
#

the guild_id column is a text type

blissful sparrow
#

would it be better if I changed to int?

boreal ravine
#

yes

green bluff
quick gust
#

BIGINT, sure because it makes the most sense

boreal ravine
#

change it to BIGINT though

blissful sparrow
#

dont think sqlite supports bigint

green bluff
#

and also its a good practice to add trailing commas to one elment tuples

blissful sparrow
#

nvm

green bluff
#

instead of message.guild.id do message.guild.id,

boreal ravine
blissful sparrow
#

I would add this to mariadb but the stupid connector says refused despite connecting from a user thats whitelisted on all ips

#

I dont need to add str still do I?

green bluff
#

not after changing it to int

blissful sparrow
quick gust
#

inside the tuple of course

vale wing
blissful sparrow
#

I believe thats worked guys thanks so much!

quick gust
#

yw

vale wing
blissful sparrow
#

I would add a way to drop a row once bot leaves a guild but it seems a bit like a sticky one

vale wing
#

Just put strict WHERE cond

quick gust
#

thats easy

vale wing
#
DELETE FROM guilds WHERE id = ...```
blissful sparrow
#

Im coding after what, 4 years?

#

so ive forgotten a lot

vale wing
#

You always have time to remember it 👍

blissful sparrow
#

not when youre a medical student

vale wing
#

Ah yes

blissful sparrow
#

how hard would it be to port from sqlite to aiosqlite?

#

Cos my main aim is to use aiosqlite but I wanted to get something up n running first

quick gust
#

not very hard, it's just an async bridge

#

so nothing will change except stuff will need to be awaited like

await c.execute(...)```
blissful sparrow
boreal ravine
#
await execute(...)

await connect(...)
blissful sparrow
#

eh?

#

how would I do that

#

there is no connect()

#

apart from the initial one

green bluff
#

and c = await conn.cursor

#

and result = await c.fetchone()

blissful sparrow
#

Oh I see I didn't think that was allowed

#

Ive only started messing with async when I started this project

blissful sparrow
#
AttributeError: 'Result' object has no attribute 'execute'
C:\Python310\lib\site-packages\discord\client.py:380: RuntimeWarning: coroutine 'Connection.cursor' was never awaited
  await self.on_error(event_name, *args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
#

oh wait

#

line 15

#

I been up all night doing dis XD

#

Thanks @green bluff and @boreal ravine

#

one last thing

#
   @commands.command()
   @commands.check_any(
        commands.is_owner(),
        commands.has_permissions(administrator=True))
    async def rsay(self, ctx, channel:discord.TextChannel=None, *, message):
        if commands.check_any()==True:
            await ctx.message.delete()
            if channel != None:
                await channel.send(str(message))
            else:
                await ctx.reply("Please provide a channel.")
        else:
            await ctx.reply("lol no")
#

it replies the lol no

#

despite being owner

#

how do i do the check?

boreal ravine
blissful sparrow
#

how else would I get it to reply with lol no

#

if they dont have the perms

torn sail
#

It will raise an error

#

And you catch it in an error handler and do something

#

!d discord.ext.commands.CheckAnyFailure

unkempt canyonBOT
#

exception discord.ext.commands.CheckAnyFailure(checks, errors)```
Exception raised when all predicates in [`check_any()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check_any "discord.ext.commands.check_any") fail.

This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

New in version 1.3.
blissful sparrow
#

I believe I already have that in my errorhandler

manic blade
#

highest_salaries = salary.sort_values(by='salary', ascending=False)
eighth_highest_salary = tenpaid.get['salary'].index[9]
eighth_player_name = tenpaid.get['name'].index[9]
print('Player:', eighth_player_name, '\nSalary:', eighth_highest_salary)

blissful sparrow
manic blade
#

what is the issue with this code?

blissful sparrow
manic blade
boreal ravine
shrewd shell
#

Hello, I'm looing to discuss with someone about the intents.json, and if or how to implement entities?

blissful sparrow
#

#help-the-basement

shrewd shell
#

how the chat bot does the conversation

#

oh sorry, I should mention i'm trying to make a chatbot work

slate swan
#

Well you don't need to use a json to define your intents

#

!d discord.Intents

unkempt canyonBOT
#

class discord.Intents(**kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions"), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").

New in version 1.5...
slate swan
#

Is the class you will use

#

Since you are making a chatbot you would need Intents.default() along with Intents.message_content

blissful sparrow
#

Is there a way to fetch a guild's name and owner from an id?

#

if the bot is not in said guild

quick gust
#

I don't believe so

slate swan
blissful sparrow
#

Rip

slate swan
#
async def join(ctx):
  channel = bot.get_channel(940989023105712178)
  await channel.connect()```

```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'connect'```
slate swan
cloud dawn
slate swan
slate swan
#

Help me

#

cogs/music.py

from discord.ext import commands

class Radio(commands.Cog):
  def __init__(self, client):
    self.client = client
    
  @commands.command()
  async def join(self, ctx):
    channel = ctx.author.voice.channel
    if ctx.author.voice != None:
      channel.connect()
      await ctx.send('Successful')
    else:
      await ctx.send('Pls join to voice channel')
      
def setup(client):
  client.add_cog(Radio(client))```
cloud dawn
#

Sorry we don't help with music bots.

slate swan
#

main.py

import os
from discord.ext import commands

client = commands.Bot(command_prefix='+',help_command=None,activity=discord.Game(name='Дристаю толчёк 24/7'))

@client.event
async def on_ready():
  print('Bot online')

for filename in os.listdir('./cogs'):
  if filename.endswith('.py'):
    client.load_extension(f'cogs.{filename[:-3]}')

token = os.environ.get('Token')
client.run(token)```
abstract kindle
#

any way to get role icons?

vale wing
#

One sec

vale wing
abstract kindle
#

:/

vale wing
#

!d disnake.Role.icon

unkempt canyonBOT
#

property icon```
Returns the role’s icon asset, if available.

New in version 2.0.
abstract kindle
#

that's okay

vale wing
#

!d discord.Role.icon

unkempt canyonBOT
#

property icon```
Returns the role’s icon asset, if available.

Note

If this is `None`, the role might instead have unicode emoji as its icon if [`unicode_emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role.unicode_emoji "discord.Role.unicode_emoji") is not `None`.

If you want the icon that a role has displayed, consider using [`display_icon`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role.display_icon "discord.Role.display_icon").

New in version 2.0.
vale wing
#

Oh this exists as well

abstract kindle
#

Oh

slate swan
# slate swan Help me

just include await before channel.connect()
copy this if you don't get it

from discord.ext import commands

class Radio(commands.Cog):
  def __init__(self, client):
    self.client = client
    
  @commands.command()
  async def join(self, ctx):
    channel = ctx.author.voice.channel
    if ctx.author.voice != None:
      await channel.connect()
      await ctx.send('Successful')
    else:
      await ctx.send('Pls join to voice channel')
      
def setup(client):
  client.add_cog(Radio(client))```
slate swan
spring flax
#

channel = ctx.author.voice.channel

slate swan
#

ah i only saw await error on his shell

spring flax
#

Yeah you'd have to do if member.voice: channel = ...

slate swan
#

anyway
await ctx.guild.change_voice_state(self_mute=True, self_deaf=True)
this thing is not working

placid skiff
#

i doubt that guild has a change_voice_state method

#

!d discord.Guild.change_voice_state

unkempt canyonBOT
#

await change_voice_state(*, channel, self_mute=False, self_deaf=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Changes client’s voice state in the guild.

New in version 1.4.
placid skiff
#

oh it has hahahaha

#

you didn't specified the channel

slate swan
#

yeah

spring flax
slate swan
#

ah

#

got it

#

still don't work
await ctx.guild.change_voice_state(channel=channel, self_mute=True, self_deaf=True)

#

it seems like this line is getting ignored

#

no error

umbral night
#

is there a way for a bot to pin a message?

#

how would i go about doing that?

cloud dawn
#

!d discord.Message.pin

unkempt canyonBOT
#

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

Pins the message.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to do this in a non-private channel context.
umbral night
placid skiff
slate swan
#

yes

#
async def join(ctx):
  channel = bot.get_channel(940989023105712178)
  await channel.connect(timeout=99999999)
  await ctx.guild.change_voice_state(channel=channel, self_mute=True, self_deaf=True)```
cloud dawn
placid skiff
#

it connects to te channel right?

slate swan
slate swan
spring flax
#

I don't think you need to do channel.connect

slate swan
spring flax
#

Try removing that line and only keeping the other maybw

#

Keep the change_voice_state

umbral night
placid skiff
#

or try first to change the voice state then connect

umbral night
spring flax
#

You don't

slate swan
# spring flax Keep the change_voice_state

yes working fine now

async def join(ctx):
  channel = bot.get_channel(940989023105712178)
  # await channel.connect(timeout=None)
  await ctx.guild.change_voice_state(channel=channel, self_mute=True, self_deaf=True)```
spring flax
#

Cool

umbral night
spring flax
#

You have to define message

#

Not pin

umbral night
#

oh

umbral night
#

or something else

spring flax
#

Sure if that's what you want to pin

umbral night
#

ight

#

still doesnt work

umbral night
placid skiff
#

pin is a method

#

nop

#

!d discord.Message.pin

unkempt canyonBOT
#

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

Pins the message.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to do this in a non-private channel context.
umbral night
abstract kindle
#

can clicking a button take you to a different channel

#

or is that not possible

umbral night
cloud dawn
umbral night
#

oh

#

lol

cloud dawn
umbral night
#

thank you

slate swan
#

how would i print an embed?
like i got code like this

@commands.Cog.listener()
async def on_message(self, message):
    print(message)

and i wanna check if message has an embed and if yes then print embed title

#

for example i wanna print Members part of this command

supple thorn
#

!d discord.Message.embeds

unkempt canyonBOT
slate swan
#

Alr thanks

umbral night
#

how would i make a reminder command? so i could do !remind (time till bot reminds) (text)

supple thorn
#

And have a task to check if any of the reminders time is up

#

And remind them

junior verge
supple thorn
junior verge
#

Why not? If your bot doesnt go offline

#

Its easy for small bots

supple thorn
vale wing
#

If your duration is like < 100 seconds maybe that's ok

#

Otherwise no definitely

#

If many users use your reminder command it will cause problems

supple thorn
#

It's better to just go with tasks and a database than to risk losing all of the data because your bot died

cloud dawn
#

Hmm how about going at the CommandTree on_error? Best to subclass it i guess?

slate swan
#

is on_error a method of CommandTree ?( yes im aware its an event too)

cloud dawn
#

I'm using Client so cogs is not really an option right now.

slate swan
#
async def my_handler(...):
    ...

command_tree = app_commands.CommandTree(...)
command_tree.on_error = my_handler
``` you can do this if you dont want to subclass..
cloud dawn
#

What do you think?

slate swan
#

i prefer subclassing most of the things, but since i've never used discord.py's app commands cant say

cloud dawn
#

Been using it for about 3 days but it's pretty messy.

slate swan
#

i honestly dont like the implementation

cloud dawn
#

Logically you would use Client with the slash commands but without cogs you need to make your own Group solution.

cloud dawn
#

But since you can't do that in discord.py Bot class is pretty useless and annoying.

#

Thus now working with Client I don't have cogs as well as listeners. ducky_drawing

slate swan
#

that sucks, well you can make the command trees in different folders and import to add them maybe

#

if that works?!

cloud dawn
#

Which is the same as the cogs but without the reloading and unloading etc. Didn't use unload but reloading was kinda nice.

slate swan
#

well thats kinda efficient

#

but still it would be really better if there was something like cogs for this

cloud dawn
#
from discord import Interaction
from discord.app_commands import Group, command, describe, check

from decorators import is_bot_owner
from log import log
from ui.buttons import Confirm
from utils.view import inter_timeout


class Core(Group, name="core"):
    """Core functionality of the bot"""

    @command(name="stop", description="Shutdown the bot")
    @describe(forced="Forced shutdown of the bot")
    @check(is_bot_owner)
    async def _stop_bot(self, interaction: Interaction, forced: bool = False) -> None:
        view = Confirm(
            conf_msg="Shutting down the bot.",
            canc_msg="Canceled bot shutdown."
        )

        await interaction.response.send_message("Are you sure you want to shut the bot?", view=view)

        if await inter_timeout(interaction, view) and view.value:
            log.info("Shutdown command received")
            if forced:
                exit(0)
            await interaction.client.close()
#

This is my "cog"

#

Just one command for now, I'm making the base first, thinking about how to structure it, currently busy with the error system then the DB and then I can add more cmds

slate swan
#

ah cool :D
and what about the command options, how do you get that done?

cloud dawn
slate swan
#

like thats a slash command isnt it, how do you take arguments from user

cloud dawn
#

Ah with args & kwargs plus typehint

#

for example the forced kwarg here is optional and it's only a bool

#

So the typehint is the datatype and after the equal will be the representing default value.

#

You can also assign it to a function and change the name and do even bigger Params if you wanna get real fancy.

slate swan
#

the Group class looks like cogs but meant for a commandtree

#

also, what if you use Bot with a command tree and without message_content intents, does it error out or something?

cloud dawn
#

Since command_prefix basically is reading a message.

#

But the bot currently has 0 intents on

slate swan
#

you can just override Bot's on_message event and it wont try reading the content

cloud dawn
#

Tbh that sounds like a big mess

#

I just need to figure out a lot of stuff like how to get multiple groups and reloading groups for both I got an idea.

#

I was thinking about using the importlib for the import walk trough the dirs looking for the Group subclass and for the debug commands i was thinking about re-syncing for the specific set guild since you can re-sync per Group when passed.

#

But seeing as such, this is not really beginner friendly at all since most people will likely just put everything in one file to avoid all of these issues.

cloud dawn
#

Idk if many people are interested in creating slash commands anyways.

bleak karma
#

hi can i ask aiosqlite questions here

slate swan
#

hello im wondering how you can make a python discord bot online 24/7

oblique cobalt
kindred drum
#

yo how do I check who banned a user?

slate swan
kindred drum
#

whats the check tho

#

like I have this for on_member_leave:

#
try:
            banned = await member.guild.fetch_ban(member)
            
        except discord.NotFound:
            banned = False``` but how do I get who banned them
oblique cobalt
slate swan
#

audit logs

gilded gust
#

Is there a way to check if a user has permissions by using the user object itself?

kindred drum
#

:/

#

that is so complex 😭

gilded gust
#

Oh

slate swan
#

you can get the member for that user and then get the perms tho

#

!d discord.Guild.get_member , user.id goes here

unkempt canyonBOT
#

get_member(user_id, /)```
Returns a member with the given ID.

Changed in version 2.0: `user_id` parameter is now positional-only.
slate swan
#

and then you can do member.guild_permissions

gilded gust
#

got it

#

thank you!

slate swan
unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
slate swan
#
@client.command()
async def select(ctx):
    await ctx.send(
        "Selects!",
        components=[
            Select(
                placeholder="Select something!",
                options=[
                    SelectOption(label="Yes", value="a"),
                    SelectOption(label="No", value="b"),
                ],
                custom_id="select1",
            )
        ],
    )

    interaction = await client.wait_for(
        "select_option", check=lambda inter: inter.custom_id == "select1"
    )
    await interaction.send(content=f"{interaction.values[0]} selected!")

this is my code i get no errors but the command is unresponsive

#

also i didnt used on_message in any other parts of my code

#

arent they checking it when a member is removed tho?

velvet haven
#

discord api is blocking my bot for some reason can anyone help

slate swan
#

wrong event tho

velvet haven
#

yes

slate swan
#

stop using replit
temporary solution: type kill 1 in shell

#

Help me

#

cogs/music.py

from discord.ext import commands

class Radio(commands.Cog):
  def __init__(self, client):
    self.client = client
    
  @commands.command()
  async def join(self, ctx):
    channel = ctx.author.voice.channel
    if ctx.author.voice != None:
      await channel.connect()
      await ctx.send('Successful')
    else:
      await ctx.send('Pls join to voice channel')

@commands.command
async def leave(self, ctx):
  if ctx.voice_client == None:
    await ctx.send('Bot is not in voice channel')
  else:
    await ctx.voice_client.disconnect()
    await ctx.send('Bot is disconnected')
      
def setup(client):
  client.add_cog(Radio(client))```
velvet haven
slate swan
#

self host/vps

slate swan
slate swan
heady sluice
spring flax
#

How can you stop and restart a bot with python?

heady sluice
#

stop the script with sys?

#

or by only using cogs

proud rain
#

in on_user_update color=self.log_channel.guild.get_member(after.id).colour, AttributeError: 'NoneType' object has no attribute 'colour'

Why am i keeping getting this error? - The stuff works, but i keep getting this error.

slate swan
#

You don't have member intents

#

or after.id is an invalid Id for the guild

spring flax
proud rain
proud rain
spring flax
#

!intents

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 the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

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

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

from discord import Intents
from discord.ext import commands

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

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

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

proud rain
#

i have this in the main file

slate swan
proud rain
spring flax
#

Main file and discord developer portal

proud rain
#
intents = discord.Intents.all()
intents.members = True```
#

i have it, but not in the cog, should i also have in the cog?

spring flax
#

If you explicitly enable all, you don't need to set members to True

proud rain
#

okay, so i should just delete that?

spring flax
#

Yes it's unnecessary

proud rain
#

Im gonna check if it work :)

spring flax
spring flax
boreal ravine
#

O

proud rain
boreal ravine
#

no

#

what raven said

proud rain
#

then what you mean

proud rain
spring flax
#

You're doing guild.get_member in a user update event?

spring flax
#

Cool

proud rain
#

or wait, i should test it a little more

#

Omg, its working, thanks!!

spring flax
#

although

#

can you send your full code? @proud rain

proud rain
#

ofc

#

but why

spring flax
#

to see something

unkempt canyonBOT
#

Hey @proud rain!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

spring flax
#

You can use this !paste

#

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

proud rain
#

But what should you need it for?

spring flax
slate swan
#

what's the best lyrics api guys

spring flax
#

a discord.User is a any discord user, he doesn't have to be in the guild that the command is invoked in or your guild where you're testing. For this, you'd need discord.Member

#

doing user.color will always return the default color by the way

#

so you don't need that

proud rain
#

so what should i change

#

im gonna eat dinner, coming back in 10 minutes or more

spring flax
#

i'm just saying that if the member isn't in the guild that the self.log_channel is in, there will be an error

#

saying member not found

heady sluice
#

discord dropdowns same as disnake dropdowns?

spring flax
#

because you're using guild.get_member on a user

spring flax
heady sluice
#

not the behaviour

#

how you make them

spring flax
#

not sure that haven't used dpy since it was stopped

#

i don't like some of the things they're doing

heady sluice
#

I switched back

#

I had to await setups and load_extensions

#

it worked instantly

#

I'm impressed

spring flax
#

maybe they have a example on the github?

heady sluice
#

lemme check

#

yeah they are exactly the same

#

Copyright (c) 2015-present Rapptz

#

so that's why disnake has the same dropdowns

boreal ravine
#

it's a fork after all

heady sluice
#

ok Imma start slash commands for a good sake

boreal ravine
#

nice

heady sluice
#

so many people are asking here about them aswell

boreal ravine
#

d.py's slash command impl < disnake's slash command impl

heady sluice
#

don't care won't care

#

they don't have an app commands example

boreal ravine
#

they do

#

check the gist

pliant gulch
# heady sluice Copyright (c) 2015-present Rapptz

That doesn't really change anything, the code base is licensed under MIT, so it's VERY permissive. Forks just need to include the copyright notice and they can literally change every aspect of the library

heady sluice
#

but they didn't

#

so it makes sense

proud rain
#

@spring flax

spring flax
#

what

vale wing
heady sluice
#

dpy

#

I'm searching

vale wing
#

Ah yes it's in a gist

heady sluice
#

where

vale wing
#

Lemme fetch a link for you

heady sluice
#

I'm making my app commands from this

vale wing
heady sluice
#

it's useful

vale wing
#

Nvm sorry it's not that

heady sluice
#

f

vale wing
heady sluice
#

do you think this is good

vale wing
#

I dunno I use disnake

heady sluice
#

ay I was quite close

proud rain
vale wing
#

But it's supposed to be bot.tree

#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
heady sluice
#

works too

vale wing
#

See how they define client

heady sluice
#

so I got it

spring flax
proud rain
vale wing
#

We typically use commands.Bot yk

#

And that has tree attribute so why not use it

heady sluice
#

so it only accepts one tree?

spring flax
#

so why put it, just remove the color kawrg.

heady sluice
#

logically

vale wing
#

I don't really know about slash commands in dpy sorry

heady sluice
#

me neither bro

placid skiff
heady sluice
#

me neither

proud rain
spring flax
#

it's in your code

proud rain
#
    @Cog.listener()
    async def on_user_update(self, before, after):
        if before.name != after.name:
            embed = Embed(title="Navne Skifte",
                          colour=after.colour,
                          timestamp=datetime.utcnow())

            fields = [("Før:", before.name, False),
                      ("Efter:", after.name, False)]

            for name, value, inline in fields:
                embed.add_field(name=name, value=value, inline=inline)
                embed.set_footer(text=f'{after.author.display_name}')


            await self.log_channel.send(embed=embed)

        if before.discriminator != after.discriminator:
            embed = Embed(title="Discriminator Skifte",
                          colour=after.colour,
                          timestamp=datetime.utcnow())

            fields = [("Før:", before.discriminator, False),
                      ("Efter:", after.discriminator, False)]

            for name, value, inline in fields:
                embed.add_field(name=name, value=value, inline=inline)
                embed.set_footer(text=f'{after.author.display_name}')


            await self.log_channel.send(embed=embed)

        if before.avatar_url != after.avatar_url:
            embed = Embed(title="Profilbillede Skifte",
                          description="Nyt billede er nedenunder, og gamle er til højre.",
                          color=self.log_channel.guild.get_member(after.id).colour,
                          timestamp=datetime.utcnow())

            embed.set_thumbnail(url=before.avatar_url)
            embed.set_image(url=after.avatar_url)




            await self.log_channel.send(embed=embed)```
placid skiff
vale wing
spring flax
heady sluice
#

discord.errors.ClientException: This client already has an associated command tree.

#

I should change how I do that though

vale wing
#

Use bot.tree don't create new one ig

heavy folio
#

bot has a tree already

placid skiff
heady sluice
#

so it cannot have more

proud rain
heavy folio
#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
vale wing
#

And yeah it has app_command decorator I am pretty sure

proud rain
heavy folio
heady sluice
heavy folio
#

why would you need 2?

heady sluice
spring flax
vale wing
#

I mean @bot.tree.app_command

heady sluice
proud rain
heady sluice
spring flax
#

what is not working

proud rain
#

i just tried switching profile pic, and it didnt send

vale wing
#

Eh wait there's no such thing yea

heady sluice
#

I see add_command in every example

spring flax
#

so what is the error

heady sluice
#

bot.tree.add_command Ig

proud rain
heavy folio
#

!d discord.on_user_update is a thing

unkempt canyonBOT
#

discord.on_user_update(before, after)```
Called when a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") updates their profile.

This is called when one or more of the following things change:

• avatar

• username

• discriminator...
heavy folio
#

idrk if you need intents or not tho

spring flax
#

okay you said that already

#

but that's not what I asked

#

what's the error?

proud rain
#

there isnt a error

#

thats also the problem

heady sluice
#

the bot launched, how do I know it's being registered?

vale wing
#

!d discord.app_commands.CommandTree.command

unkempt canyonBOT
vale wing
#

There

#

The decorator

heady sluice
#

got it

vale wing
heady sluice
#

have you used app commands in disnake?

vale wing
#

And I heard something like you need to call tree.sync

vale wing
#

Cause it's more high level

#

Dpy is like low-level and it usually means less convenient but more control

heady sluice
austere solstice
#

error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice
help pls

slate swan
velvet haven
#

Is replit the only way of building a bot

supple thorn
#

I wonder how easy though

supple thorn
#

Definitely no but what do you mean build a bot

velvet haven
#

I want the bot to stay online even after terminating my program

supple thorn
velvet haven
#

Then what am I supposed to use

supple thorn
#

If you want to make your bot be on 24/7 be prepared to spend money

#

Or get a sugar daddy

quaint scaffold
#

iirc Azure / AWS offer free trials, but you will need to put in a credit card to verify you're human. This is normal across all free tier offering services. @velvet haven

boreal ravine
#
pip install pynacl
austere solstice
winged bone
#

Hi, do you know what the atomic argument of Member.add_roles does in dpy?

#

In the docs it says: atomic (bool) – Whether to atomically add roles. This will ensure that multiple operations will always be applied regardless of the current state of the cache.

#

I don't understand that 😶

velvet haven
#

I just watched a youtube on how to create a bot using replit

fading kestrel
#

@velvet haven

velvet haven
#

Yep

fading kestrel
#

Search it up on Yt for help on it

supple thorn
fading kestrel
#

Why

supple thorn
#

Replit isn't even meant for hosting

boreal ravine
fading kestrel
#

You can make it tho

#

Doesn’t really matter

supple thorn
fading kestrel
#

Anyways I gtg cya y’all

supple thorn
#

A shit

#

@fading kestrel

heady sluice
#
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.all(), help_command=None)

@bot.event
async def on_ready():
    print(discord.__version__)
    print("Gotchu homie.")

@bot.event
async def on_command_error(ctx: commands.Context, error: Exception):
    #some handling

@bot.tree.command()
async def hello(interaction):
    print(type(interaction))

@bot.command()
async def load_cogs(ctx):
    #load cogs
    await bot.tree.sync()

bot.run(TOKEN)
```any reason why my hello command isn't registered?
supple thorn
#

Oh shit i'm sorry raven if i pinged you

boreal ravine
heady sluice
#

I'll check

spring flax
#

that's fine

spring flax
heady sluice
#

so probably

#

that what you meant?

boreal ravine
#

no

#

scope

heady sluice
#

f

#

Imma reinvite

#

invited like this but still no

boreal ravine
#

anyone here in the epikhost server?

slate swan
#

helo?

#

can someone help me?

heady sluice
#

yes

slate swan
#

thancks

#

bro

heady sluice
#

ask

slate swan
#

okay

#

whats the error in this

#

if any(word in msg for word in sad_words):

heady sluice
#

word in msg.content?

slate swan
#

i am using replit

heady sluice
#

okay but not related

slate swan
#

msg = message.content i gave this already

heady sluice
#

then it's okay

#

sad_words is?

#

is it a list in your command's scope?

slate swan
#

sad_words = ["sad", "depressed", "unhappy", "angry", "miserable", "depressing"]

heady sluice
#

where did you define that

slate swan
#

in the starting

heady sluice
#

show the whole command

slate swan
#

ok

#

import discord
import os
import json
import requests
import random

client = discord.Client()

sad_words = ["sad", "depressed", "unhappy", "angry", "miserable", "depressing"]

starter_encouragements = [
"Cheer up!",
"Hang in there."
"You are a great person!"
]

def get_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = json.loads(response.text)
quote = json_data[0]['q'] +" -" + json_data[0]['a']
return(quote)

@client.event
async def on_ready():
print ('We Have Logged In As {0.user}' .format(client))

@client.event
async def on_message(message):
if message.author == client.user:
return

if msg.content.startswith('Inspire'):
quote = get_quote()
await message.channel.send(quote)

msg = message.content

if any(word in msg.content for word in sad_words):
awaitmessage.channel.send(random.choice(
starter_encourangements))

client.run(os.getenv('TOKEN'))

scarlet aurora
#

code block it

#

py

heady sluice
#

okay, sad_words is not in your on_message's scope

slate swan
#

and, bad tutorial.

heady sluice
#

actually

slate swan
#

xd

heady sluice
#

your on_message ended at msg = message.content

#

so it's an indentation issue

buoyant igloo
slate swan
#

so what do i do?

heady sluice
#

which I would recommend learning python for

slate swan
heady sluice
#

indent msg = message.content

#

!indentation

#

we're botless

buoyant igloo
#

How ironic

slate swan
#

bro can someone teach me python

heady sluice
#

it's probably being maintained

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

heady sluice
#

what

#

we have a bot, just workingn't

slate swan
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

buoyant igloo
#

And do projects like this it’s helpful

heady sluice
slate swan
heady sluice
#

!indention

#

!indent

#

so only indents

#

how unprofessional

slate swan
dusky pine
#

so aliases = professional?

#

lmao

heady sluice
#

you got it

buoyant igloo
heady sluice
slate swan
#

whos Corey well hes a goat 😎

buoyant igloo
slate swan
#

😳

heady sluice
#

so
aliases != professional
not knowing Corey Schafer = not a programmer

slate swan
#

Yep

heady sluice
#

seems like a nice guy

slate swan
#

k

slate swan
#

ive seen live streams hes a pretty chill guy

slate swan
#

havent seen lucas code in a while

#

🤨 🤨 🤨 🤨

heady sluice
#

oh but seen swastik more than needed

heady sluice
#

bot > client

slate swan
#

listen

#

it's still showing the error

heady sluice
#

and for myself,
slash commands != work

slate swan
#

the error is all your code

heady sluice
slate swan
#

its horrible no good code

slate swan
heady sluice
#

rude

slate swan
heady sluice
slate swan
heady sluice
#

show

slate swan
# heady sluice rude

im not being rude its just not the best code at all which can be done better. not from a yt tutorial

heady sluice
#

unexpected indented block?

#

okimi

slate swan
#

?

heady sluice
#
@bot.tree.command()
async def hello(interaction):
    print(type(interaction))

@bot.command()
async def load_cogs(ctx):
    for extension in os.listdir("cogs"):
        if extension.startswith("cog"):
            await bot.load_extension(f"cogs.{extension[:-3]}")
            print(f"Loaded {extension[:-3]}")
    await bot.tree.sync()
```registeredn't
slate swan
#

i dont use master

heady sluice
#

use master

#

so you can tell me why it isn't registered

slate swan
#

:kek: you guys going back to dpy?

heady sluice
#

only me

heady sluice
#

and all intents

slate swan
#

and waited for 1 hr?

heady sluice
#

1hr?

slate swan
#

yea, the globals take 1 hr to register...

#

if its guild specific it gets added right at the moment

heady sluice
#

discord still frightens me

#

what if I close the script now and pass a guild to tree.sync()

slate swan
#

the command will be created

heady sluice
#

oh wait I didn't even invoke the command which syncs

#

god damnit me

#
@bot.tree.command()
async def hello(interaction):
    print(type(interaction))

@bot.command()
async def load_cogs(ctx):
    for extension in os.listdir("cogs"):
        if extension.startswith("cog"):
            await bot.load_extension(f"cogs.{extension[:-3]}")
            print(f"Loaded {extension[:-3]}")
    await bot.tree.sync(guild=ctx.guild)
#

and command invoked

#

slash commandn't so I'm waiting

cloud dawn
heady sluice
#

no

cloud dawn
#

You don't need bot to make slash commands

heady sluice
#

I have normal commands

cloud dawn
#

Using Bot acc make slash command obsolete lol

quaint epoch
cloud dawn
heady sluice
quaint epoch
heady sluice
#

b ain't there anyways

quaint epoch
#

what's your point?

heady sluice
#

?

quaint epoch
heady sluice
#

to have slash commands

quaint epoch
#

who even uses builtin slash commands anyway

heady sluice
#

NOBODY

#

I WANT MY OWN

quaint epoch
#

slash has no real incentive, like nfts

heady sluice
#

god this is beginning to be annoying

cloud dawn
quaint epoch
#

no

#

what arguments do you have?

cloud dawn
heady sluice
#

other people can't see it

quaint epoch
#

you can't typehint a lot of stuff, like members, guilds, or things to slash commands

heady sluice
quaint epoch
#

which is mildly annoying

cloud dawn
heady sluice
#
  • discord forces you to it
cloud dawn
quaint epoch
quaint epoch
#

indeed

cloud dawn
heady sluice
#

still won't stop me

quaint epoch
#

only heard of this, slash commands mandated fiasco after a month

cloud dawn
#

How is that Discords fault?

heady sluice
#
@tree.command(guild=discord.Object(id=MY_GUILD_ID))
async def range(interaction: discord.Interaction, value: app_commands.Range[int, 1, 100]):
    await interaction.response.send_message(f'Your value is {value}', ephemeral=True)
```ah I see
quaint epoch
#

which was after 60+ of my commands were not compatible after just changing @commands.command to @commands.slash_command

quaint epoch
#

i just don't see why they have to be mandated

cloud dawn
quaint epoch
#

like, mee6 for example

cloud dawn
heady sluice
#

don't you think MEE6 has connections to discord

slate swan
#

you do that when you try to whitelist your bot ( verify)

cloud dawn
quaint epoch
cloud dawn
quaint epoch
#

cya

slate swan
cloud dawn
#

Most likely the message intents will be really sensitive, so most likely you can't use custom prefixes anyways.

slate swan
#

if you request for message intents, the verification is gonna be very specific about everything

quaint epoch
slate swan
#

this is what i was asked for

cloud dawn
#

Damn a code-snippet of your most used command, aka determine the skill of the programmer Discord do be strict.

maiden fable
slate swan
#

what intents did you ask for?

quaint epoch
maiden fable
#

Eh, u can share the snippet for any command

cloud dawn
#

Why do you want message intents tough?

maiden fable
#

I got them both (:

slate swan
#

cool enough

heady sluice
slate swan
#

but ill now stick to slash commands only

maiden fable
#

Wbu @slate swan

#

What intents?

cloud dawn
#

I'm trying to make a 0 intents bot.

maiden fable
#

Oh, cool

heady sluice
#

that sounds

slate swan
heady sluice
#

API calling

slate swan
maiden fable
#

Breh

#

Btw what's ur reviewer name? @slate swan

heady sluice
#

actually, intents do lots of API calls on startup, right?

maiden fable
#

No?

heady sluice
#

then how do they get the data?

maiden fable
#

It's literally just sending the READY payload with the intents key

slate swan
maiden fable
#

I mean, not as simple as that but that's the crux

maiden fable
heady sluice
#

oh discord returns it all in one

unkempt canyonBOT
#

discord/state.py line 161

class ConnectionState:```
heady sluice
#

cuz this is what client._connection gets

#

with intents and stuff

blissful sparrow
#

why is it when I do

bot = commands.Bot(command_prefix=commands.when_mentioned_or(get_prefix), intents=intents)

it gives the error TypeError: tuple for startswith must only contain str, not function

but when I do

bot = commands.Bot(command_prefix=get_prefix, intents=intents)

it works fine?

#

how would I go about fixing it so when bot gets mentioned it replies with the set prefix?

slate swan
#
return commands.when_mentioned_or("the prefix")(bot, message)
``` in your get_prefix function
#

!d discord.Member.activity

unkempt canyonBOT
#

property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
slate swan
#

you can use the .name attribute to get the name

heady sluice
#

how do you handle this?
discord.app_commands.errors.CommandNotFound: Application command 'hello' not found

#

really bad question

#

lmao

heady sluice
#

cuz you have interaction, not ctx

#

so it's weird to have it in on_command_error

#

and I did so, it wasn't handled

blissful sparrow
#

are you trying to add slash command?

heady sluice
#

no it's added

blissful sparrow
#

check indentation maybe?

#

cos its not registering whatever it is

#

as a slash command

heady sluice
#

but incase it wasn't resynced after the command is registered, it throws an app command not found error

#

it's registered

#

if it wasn't, it would just be sent as a message

#

but if I remove the command again, and I don't resync, it throws this error

blissful sparrow
#

I need to learn to add slash commands still

blissful sparrow
slate swan
#

you would have to use a on_message event for that

#

!d discord.Message.mentions check if bot.user is in the mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

slate swan
#

no, thats not how you take an argument in python

slate swan
#
async def function(member: discord.Member):
   activity = member.activity```
heady sluice
#

right, you can't typehint to guild

#

but you can to member

#

but why would you typehint to a guild

blissful sparrow
#
@bot.event
async def on_mentions(bot,ctx,):
    if ctx.bot.mentions:
        embed = discord.Embed(titlle='The current prefix for this server is: ', description=f'{get_prefix}', color=0x000000)
        await ctx.reply(embed=embed)
        return

    else:
        return

not sure what to do here

lofty pecan
#

Hello there, I would like the know what's the easiest way to display the prefix of the bot for a set server in its name?

blissful sparrow
#

by editing its server name

lofty pecan
#

Considering that I have a Json file for each server

slate swan
unkempt canyonBOT
#

property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
lofty pecan
#

Mmh

slate swan
#

And use .edit(nickname=new nickname)

blissful sparrow
#

can bots edit their own server names?

lofty pecan
#

Ah nice !

blissful sparrow
#

damn

#

Ill have to incorp that thanks for the idea

lofty pecan
#

And then that thing.edit

#

So
user = ctx.guild.me
user.edit(nickname=new nickname)

#

Is that right?

#

And I could do that in the set up function

oblique axle
#

guys i want to start to build a bot but idk how to start

slate swan
slate swan
slate swan
oblique axle
#

yes 3 months

heady sluice
#
import discord
from discord import app_commands
from discord.ext import commands

class Slashes(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        print(self.__cog_app_commands__)
        for command in self.__cog_app_commands__:
            self.bot.tree.add_command(command, guild=discord.Object(id=935587959095320676))
        self.bot.tree.add_command(self.Voices())

    @app_commands.command()
    async def say(self, interaction: discord.interactions.Interaction, text: str):
        await interaction.response.send_message(text)

    @app_commands.command()
    async def get_id(self, interaction, member: discord.Member):
        await interaction.response.send_message(member.id)
    
    class Voices(app_commands.Group):
        @app_commands.command()
        @app_commands.describe(name="Egy név")
        async def name(self, interaction, name: str):
            await interaction.response.send_message(f"A voice channeled neve mostantól {name}. *(csak teszt)*")

async def setup(bot):
    await bot.add_cog(Slashes(bot))
```say and get_id are added but not name
#

oh I know why BRU

#

why do I ask before thinking

#
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 191, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\botok\Clanbot\Bot.py", line 48, in load_cogs
    await bot.tree.sync(guild=discord.Object(id=935587959095320676))
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\app_commands\tree.py", line 891, in sync
    data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload)
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\http.py", line 400, in request
    kwargs['data'] = utils._to_json(kwargs.pop('json'))
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\utils.py", line 600, in _to_json
    return json.dumps(obj, separators=(',', ':'), ensure_ascii=True)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3312.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3312.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3312.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3312.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Command is not JSON serializable
lofty pecan
short harbor
#

hi guys

heady sluice
#

unfortunate

short harbor
#

how can i install discord.ui ?

heady sluice
#

you only have to update dpy

#

pip install git+https://github.com/Rapptz/discord.py

short harbor
slate swan
#

Don't name your folder discord, will make you suffer

heady sluice
blissful sparrow
#
@bot.event
async def on_mentions(bot,ctx,):
    if ctx.bot.mentions:
        embed = discord.Embed(titlle='The current prefix for this server is: ', description=f'{get_prefix}', color=0x000000)
        await ctx.reply(embed=embed)
        return

    else:
        return

bot not replying w prefix

heady sluice
#

wtf

#

those parameters are really wrong, the event doesn't exist and you didn't call get_prefix

spring flax
#

Lol

heady sluice
#

also not

spring flax
#

It's on message

heady sluice
#
        return

    else:
        return
#

!d discord.Member.mentioned_in

unkempt canyonBOT
slate swan
#

don't use mentiond_in in these type of stuff it's True even for role and everyone mentions

heady sluice
#

perhaps if bot.user.mentioned_in(message)

spring flax
#

!d discord.ClientUser.mentioned_in

unkempt canyonBOT
spring flax
#

Ah okay

spring flax
slate swan
#

Nope

heady sluice
#

so

@bot.event
async def on_message(message):
    if bot.user.mentioned_in(message):
        await message.channel.send("I was mentioned")
#

consider @bot.listen()

#

without everyone pings... idk

slate swan
#
async def on_message(message):
     if bot.user in message.mentions:
         # your stuff``` 🐢
heady sluice
#

mmmmmmm

#

sure!

#

next thing I could think of was if bot.user.mentioned_in(message) and not message.mention_everyone:

#

but yours is better

spring flax
#

Role mentions also take part

#

So, yeah

heady sluice
#

bots usually only have their role and a bots role

#

disable pings for bots role

dull terrace
#

you know i've never even thought about decoraters with making bots froggy_chill

#

are there any other ones apart from @bot.event

vocal snow
#

hello can someone help me test my little pony chat please

heady sluice
#

@bot.command()

#

??

dull terrace
#

oh yeah, ofc but are there any others

heady sluice
#

@commands.has_permissions

slate swan
#

I've been using lots of decos lately

heady sluice
#

@commands.has_role

dull terrace
#

i've only had to ever use ones for slash commands and event

heady sluice
#

how do checks work with slash commands?

slate swan
#

!d discord.app_commands.check

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
dull terrace
#

and i basically learnt all of my python knowledge through making bots

heady sluice
#

not show the slash command?

#

or an error message?

sick birch
#

I think discords experimenting with that

slate swan
#

will raise an error ( CheckFailure)

sick birch
#

Slash command permissions I mean

heady sluice
slate swan
heady sluice
#

then I'll need an error handler for slash commands

slate swan
#

!d discord.app_commands.CommandTree.on_error

unkempt canyonBOT
#

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

A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").

The default implementation prints the traceback to stderr if the command does not have any error handlers attached to it.
heady sluice
#

hu

#

gib example

torn sail
#

Subclass or decorator

heady sluice
#
async def on_error(interaction, command, error):
    #handling
bot.tree.on_error = on_error
slate swan
#

can i get help here?

heady sluice
#

yes

slate swan
#

im making a discord bot, and im trying to do a transfer command, my database is with JSON, sincerely im not viewing what is my error on code.
Error: bot don't reply and nothing happens in json
attachments:

heady sluice
#

yeah

slate swan
#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
slate swan
#

oh

heady sluice
#

oh and only bot does

slate swan
#

yea that would do

heady sluice
#

not client

slate swan
#

@slate swan can help me?

heady sluice
#

just proved people wrong

slate swan
#

proved what? 😂