#discord-bots

1 messages ยท Page 159 of 1

light violet
#

w8

#

@slate swan

shrewd fjord
#

no on_member_update now doesnt logs presence

#

complete new event created for it

light violet
#

what event

shrewd fjord
#

named on_presence_update

light violet
#

ohk lemme try

#

btw 3 sec ago it logged a bot

#

+_+ changing its sts

shrewd fjord
#

idk

#

in the docst they said that xd

slate swan
#

yea spooky is right

#

used to member update earlier ig

#

*to be

shrewd fjord
#

it used to log tho

light violet
#

still dindt log anything

#

didt*

#

ohk typo

shrewd fjord
#

u missing ur intents then

light violet
#

w8

#

worked thanks

shrewd fjord
#

!d discord.on_presence_update

unkempt canyonBOT
#

discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their presence.

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

โ€ข status

โ€ข activity

This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
shrewd fjord
slate swan
#

spooky.exe smart

shrewd fjord
#

come dm and help me ๐Ÿ”ซ

upbeat otter
slate swan
#

yes it was

#

๐Ÿ—ฟ i don't joke about anything but my existence

light violet
#
@client.event
async def on_presence_update(before, after):
  print("H")
  
  if str(before.raw_status) == "offline":
    return
  
  else:
    for g in db[f"stsgr"]:
      
      guild = client.get_guild(g)
      mem= guild.get_member(after.id)
      print(mem.name,"#2")
      vanity = db[f"{g}stsrolek"]
    
      roleid = db[f"{g}stsroler"]
      role=guild.get_role(roleid)
      print(role.name)
      try:
        bst = mem.activities[0].name
        ast = before.activities[0].name
        if vanity in bst:
          if not vanity in ast:
            await mem.add_roles(role, reason="Added Vanity In Status")
            print(after.name,"#3")
            
         
        elif vanity in ast:
          if not vanity in bst:
            if role in mem.roles:
              await after.remove_roles(role, reason="Removed Vanity From Status")
              print(after.name,"#4")
        
        
      except:
        pass

btw it isnot giving the role

#

though it is in the database

#
Traceback (most recent call last):
  File "/home/runner/Enc/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 129, in on_presence_update
    await mem.add_roles(role, reason="Added Vanity In Status")
  File "/home/runner/Enc/venv/lib/python3.8/site-packages/discord/member.py", line 1014, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
  File "/home/runner/Enc/venv/lib/python3.8/site-packages/discord/http.py", line 738, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
#

why am i getting this

bright wedge
unkempt canyonBOT
#

Whether guild presence related events are enabled.

This corresponds to the following events:

โ€ข on_presence_update()

This also corresponds to the following attributes and classes in terms of cache...

shrewd fjord
#

!remin 10m

#

!remind 10m

unkempt canyonBOT
#
Fat chance.

Sorry, you can't do that here!

bright wedge
#

Make sure you have enable the right intents!

light violet
#

no that is fixed btw what is missing access

bright wedge
light violet
#

bruh

#

it has top role with perms

shrewd fjord
bright wedge
#

Show code

light violet
#
@client.event
async def on_presence_update(before, after):
 
  print("H")
  
  if str(before.raw_status) == "offline":
    return
  
  else:
    for g in db[f"stsgr"]:
      
      guild = client.get_guild(g)
      try:
        mem= guild.get_member(after.id)
        print(mem.name,"#2")
      except:
        return
      
      vanity = db[f"{g}stsrolek"]
    
      roleid = db[f"{g}stsroler"]
      role=guild.get_role(roleid)
      print(role.name)
      
      bst = mem.activities[0].name
      ast = before.activities[0].name
      if vanity in bst:
        if not vanity in ast:
          print(after.name,"#3")
          print(guild.name)
          await mem.add_roles(role, reason="Added Vanity In Status")
          print(after.name,"#4")
            
         
      elif vanity in ast:
        if not vanity in bst:
          if role in mem.roles:
            print(after.name,"#3")
            await after.remove_roles(role, reason="Removed Vanity From Status")
            print(after.name,"#4")
        
        ```
#
if vanity in bst:
        if not vanity in ast:
          print(after.name,"#3")
          print(guild.name)```
upto this it is working
#

even it is loggin #4

bright wedge
light violet
bright wedge
#

Btw

light violet
#

ok now it is working

bright wedge
#

bot add view

light violet
bright wedge
#

Your button(s) not working after bot restart?

#

Answer first

#

Show code

shrewd fjord
#

bot.add_view()

#

should do that

bright wedge
#

Yep

shrewd fjord
#

!d discord.Client.add_view

unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
bright wedge
#

takes the buttons class ass parameter

shrewd fjord
shrewd fjord
#

ur cats are smart xd

bright wedge
#

Maybe let your cat to fix that

shrewd fjord
#

ye same as on_ready event but their works is diff

#

hm

#

yes

bright wedge
#

Buy dog and thanks me later

shrewd fjord
viral dock
#

Hello I have a question. Is there something wrong with this code bcs my bot is not responding on the command coinflip.

import discord
import random
import asyncio

#Perms
intents = discord.Intents.default()
intents.message_content = True
intents.presences = True
intents.dm_typing = True
intents.bans = True
intents.dm_messages = True
intents.dm_typing = True
intents.guild_messages = True
intents.members = True
intents.typing = True
intents.reactions = True
intents.messages = True
bot = discord.Client(intents=intents)

prefix = ""

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')
    await bot.change_presence(activity=discord.Activity(
        type=discord.ActivityType.watching, name="test"
    ))

#Heads Or Tails
@bot.event
async def on_message(message):

    if message.content.startswith(prefix + 'coinflip'):
        headortails = random.randrange(1, 3)
        if headortails == int(1):
            await message.channel.send('heads')
        elif headortails == int(2):
            await message.channel.send('tails')
        else:
            await message.channel.send('Error random module malfunctioned')

bot.run('Token')
shrewd fjord
#

hm

#

you have something problem with on_message event

viral dock
#

ohw

shrewd fjord
#

await bot.process_commands(message)

#

or @bot.listen()

#

should fix that

viral dock
#

in my bot event?

shrewd fjord
#

u can pass message ids tho

#

!d discord.TextChannel.history use this to get channel's messages

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.11)") 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") to do this.

Examples

Usage...
shrewd fjord
#

limit=10

shrewd fjord
viral dock
# shrewd fjord ye

Like this?

#Heads Or Tails
@bot.event
async def on_message(message):
    await bot.process_commands(message)
    if message.content.startswith(prefix + 'coinflip'):
        headortails = random.randrange(1, 3)
        if headortails == int(1):
            await message.channel.send('heads')
        elif headortails == int(2):
            await message.channel.send('tails')
        else:
            await message.channel.send('Error random module malfunctioned')
viral dock
shrewd fjord
#

demn u smort

shrewd fjord
viral dock
#

intents = discord.Intents.default()
intents.message_content = True
intents.presences = True
intents.dm_typing = True
intents.bans = True
intents.dm_messages = True
intents.dm_typing = True
intents.guild_messages = True
intents.members = True
intents.typing = True
intents.reactions = True
intents.messages = True
bot = discord.Client(intents=intents)

should be good isnt it?

shrewd fjord
#

print(f'We have logged in as {bot.user}')

#

it works?

viral dock
#

yes in my terminal its says: We have logged in as Community Bot#...

shrewd fjord
#

do u have multiple on_message event?

viral dock
shrewd fjord
#

that causing the prob

#

change @bot.event to @bot.listen()

shrewd fjord
#

commands?

viral dock
#

like *... not slash command

shrewd fjord
shrewd fjord
viral dock
#

after the intents I have prefix = "*"

#

import discord
import random
import asyncio

#Perms
intents = discord.Intents.default()
intents.message_content = True
intents.presences = True
intents.dm_typing = True
intents.bans = True
intents.dm_messages = True
intents.dm_typing = True
intents.guild_messages = True
intents.members = True
intents.typing = True
intents.reactions = True
intents.messages = True
bot = discord.Client(intents=intents)

prefix = "*"

@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
await bot.change_presence(activity=discord.Activity(
type=discord.ActivityType.watching, name="test"
))

#Heads Or Tails
@bot.listen
async def on_message(message):
await bot.process_commands(message)
if message.content.startswith(prefix + 'coinflip'):
headortails = random.randrange(1, 3)
if headortails == int(1):
await message.channel.send('heads')
elif headortails == int(2):
await message.channel.send('tails')
else:
await message.channel.send('Error random module malfunctioned')

#Bot Suggestions
@bot.event
async def on_message(message):
if message.content.startswith(prefix + 'suggest@'):
message_content3 = message.content
message_contentproccesed = message_content3.replace("*suggest@", "")
v = open("DCBotSuggestions.txt", "a")
v.write(" \n" + message_contentproccesed)
v.close
await message.channel.send(message_contentproccesed + " added")

if message.content.startswith('*readsugs'):
    f = open("DCBotSuggestions.txt", "r")
    readfile = f.read()
    await message.channel.send(readfile)
    f.close 

#Bot Code
f = open('CommunityBot.py', 'r')
lines = f.readlines
f.close()

@bot.event
async def on_message(message):
if message.content.startswith(prefix + 'ScriptCodeDC'):
await message.channel.send(lines)

bot.run('TOken')

shrewd fjord
viral dock
#

This is al my code

shrewd fjord
#

bruh

viral dock
#

hm?

shrewd fjord
#

u have multiple on_message event

#

change all @bot.event to @bot.listen()

viral dock
#

@bot.listen()
AttributeError: 'Client' object has no attribute 'listen'

shrewd fjord
#

then add await bot.process_commands(message) on all of em xd

viral dock
#

after the def on message?

shrewd fjord
#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.

async with x Asynchronously initialises the client and automatically cleans up.

New in version 2.0.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client").
viral dock
#

still this error:
@bot.listen()
AttributeError: 'Client' object has no attribute 'listen'

shrewd fjord
viral dock
#

await bot.process_commands(message)
AttributeError: 'Client' object has no attribute 'process_commands'

#

that is the error if I type *coinflip

naive briar
#

Only ext.commands.Bot support commands extensions

#

Client doesn't

shrewd fjord
#

@naive briar help em

naive briar
#

Which one returns it

shrewd fjord
#

he is using discord.Client obj

naive briar
#

Be more specific

#

And use asynchronous SQLite libraries so it's not blocking

shrewd fjord
#

async for message in tod_channel.history(limit=10)

naive briar
#

.history returns a async iterator

#

!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.11)") 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") to do this.

Examples

Usage...
shrewd fjord
#

either channel id incorrect

#

or doesnt exists

#

or maybe it's returning string

#

tried printing info[0]?

#

!d discord.Guild.get_channel

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.

Changed in version 2.0: `channel_id` parameter is now positional-only.
shrewd fjord
#

xd

#

u r not even fetching info bruh

#

like

#

info=c.fetchone()

#

tf

#

how can a db work like dat ๐Ÿ˜‚

#

u should add WHERE guild_id=a id

#

xd

vagrant brook
#

but isn't he listing all guilds tho

shrewd fjord
#

told if he want some specific guild

vagrant brook
#

apparently he iterated through all guilds

shrewd fjord
#

does @discord.ui.button(........., custom_id="blah blah")

#

u have that?

#

"_

#

add

naive briar
#

The error explained everything

shrewd fjord
#

also need to do timeout=None on super

#

?

silk fulcrum
#

sound like a big problem

#

first of it's fields doesn't have a name

shrewd fjord
#

nahhh

naive briar
#

No

silk fulcrum
#

embed.add_field(name="...", value="...")

naive briar
#

Read the error

silk fulcrum
#

where did I say smth about custom ids?

shrewd fjord
naive briar
#

The field needs a name

silk fulcrum
#

well, if you can't recognise that words are different...

silk fulcrum
#

if it ever worked...

naive briar
#

There's a reason why you should know how to read tracebacks before touching discord.py

silk fulcrum
#

mutually

shrewd fjord
#

Google laughing silently

#

anyone going to watch fifa? argentina vs france? :skul

silk fulcrum
#

I learnt to read tracebacks after 3 months of learning d.py (started python with it) โค๏ธ

#

Well, same for me

#

But reading tracebacks doesn't mean just read

#

almost anyone can read

naive briar
silk fulcrum
shrewd fjord
silk fulcrum
#

bad feeling

#

Computer is stupid

#

gotta deal with it

shrewd fjord
#

computer :are u sure about that

silk fulcrum
shrewd fjord
#

gimme ur address

silk fulcrum
#

AIs are different stories

shrewd fjord
#

lemme break ur pc

shrewd fjord
silk fulcrum
#

tho they still are stupider than people

shrewd fjord
#

๐Ÿซก

naive briar
#

They're smort

silk fulcrum
shrewd fjord
#

binaryyyyy

#

<3

silk fulcrum
#

HAHA im smart

shrewd fjord
#

nah it's smort*

naive briar
#

Noice ๐Ÿˆ

shrewd fjord
#

it's nice

silk fulcrum
#

im so sad

#

i have to delete the whole file

#

because a library that it's based on has become stupid or somehow broke

#

and i have commands that are using that file

shrewd fjord
#

๐Ÿฅน

silk fulcrum
slate swan
#

ofcourse it was sus

silk fulcrum
slate swan
unkempt canyonBOT
slate swan
#

this

silk fulcrum
#

ikr

#

i mean i still cant understand why is it sus

#

cus of it's docs?

slate swan
#

doesnt work and the ancient docs

ember nest
#

Anyone know how to use from discord import Fileand the import easy_pil

silk fulcrum
#

what

silk fulcrum
slate swan
#

you want to send an image created by easy-pil as a file?

ember nest
#

Exactly

#

But it's not sending and that's the problem

slate swan
#

show code

ember nest
#

Can in dm I don't want to leak it

silk fulcrum
#

leak what?

ember nest
#

The code

silk fulcrum
#

bruv

ember nest
#

I kinda worked hard on it lmao

silk fulcrum
#

which lib are u using?

slate swan
#

i'll answer here tho

#

library

ember nest
ember nest
silk fulcrum
slate swan
#

remove discord

silk fulcrum
ember nest
#

You are using @bot.slash_command ? @slate swan

silk fulcrum
#

ok yeah you should read what the error says

slate swan
#

they are using nextcord but have discord installed

slate swan
silk fulcrum
#

? yes

slate swan
#

removed discord from requirements and clear your cache in the host

silk fulcrum
#

yeah "do0ing"

ember nest
# slate swan without any errors?

Yes no errors at all unless after 3 minutes or something it gives this error
discord.errors.HTTPExecption: 413 Played Too Large (error code: 40 005) Request entity too Large

slate swan
#

you dont need to worry about grammar im the indian guy here

silk fulcrum
slate swan
silk fulcrum
#

im silent

ember nest
slate swan
silk fulcrum
ember nest
#

The image on the bot folder

slate swan
slate swan
shrewd fjord
ember nest
#

What size should I use

shrewd fjord
#

i told u earlier xd

silk fulcrum
#

maybe im just blind

slate swan
shrewd fjord
#

well what me doing idk

ember nest
slate swan
silk fulcrum
ember nest
#

U can check the current size on the dm

slate swan
#

try printing the size first

ember nest
slate swan
#

save the file locally first and check the size

shrewd fjord
ember nest
#

Bruh still same @slate swan

#

I keep resizing it smaller

#

Dude I made everything size 100 and still not working lmao

#

Even size of everything is 50 now

#

Bruh

#

Even size 20 not working.....

#
2022-12-18 15:42:34 ERROR    discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "<string>", line 64, in on_member_join
  File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/discord/abc.py", line 1536, in send
    data = await state.http.send_message(channel.id, params=params)  File "/data/user/0/ru.iiec.pydroid3/files/arm-linux-androideabi/lib/python3.9/site-packages/discord/http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 413 Payload Too Large (error code: 40005): Request entity too large
ember nest
shrewd fjord
#

cul

#

idk xd

#

i didnt use PIL for like 3 month totally forgot it

ember nest
#

Bruh

#

I don't know how to fix it either

quick gust
#

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

drifting arrow
#

is there a discord.guild.get_member_by_id? or something?

quick gust
#

I'm getting this error

Traceback (most recent call last):
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\common_bot_base.py", line 416, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "c:\Users\Admin\Desktop\Avalian\cogs\config.py", line 7, in <module>
    class Config(Cog):
  File "c:\Users\Admin\Desktop\Avalian\cogs\config.py", line 69, in Config
    async def set_autorole_role(self, ctx: Context, role: Role):
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 1371, in decorator
    result = command(name=name, cls=cls, *args, **kwargs)(func)
  File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\disnake\ext\commands\core.py", line 1631, in decorator
    raise TypeError("Callback is already a command.")
TypeError: Callback is already a command.
drifting arrow
quick gust
#

even though I don't have another command with the same name

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

oh

#

I considered trying that..

#

But I didnt think it'd be that simple

slate swan
#

you probably used the @commands.command decorator twice

quick gust
#

nah i just waited 5 mins, ran the bot again and it works ๐Ÿ—ฟ

dense merlin
#

Im new to json databases and idk the error here:

#code:
users[author] = str(author)
    users[str(author)]['Wallet'] = str(0)
    users[author]['Bank'] = 0
#err
Traceback (most recent call last):
  File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 59, in balance
    await open_account(int(author))
  File "main.py", line 77, in open_account
    users[str(author)]['Wallet'] = str(0)
TypeError: 'str' object does not support item assignment

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

Traceback (most recent call last):
  File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 876, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'bal' raised an exception: TypeError: 'str' object does not support item assignment
meager chasm
dense merlin
#

i made a file called mainbank.json

meager chasm
#

what is type of author variable

dense merlin
#

str

meager chasm
#

so users[author] = str(author)

dense merlin
#

but im not sure what to conbert it ot

meager chasm
#

is just having value same as key

dense merlin
meager chasm
#

so what is the point of that

dense merlin
meager chasm
#
users = {}
users["author name"] = "author name"
#

is what ur doing

dense merlin
#

oh

#

so how do i add aurthor to the dict

#

so i can dump it to json

meager chasm
#

are u storing it on author name or author id or

dense merlin
#

id

meager chasm
#

ok so ur data is structured like ```py
{"id": {"Wallet": 0}}

meager chasm
#

so you should do ```py
users[author_id] = {"Wallet": 0}

dense merlin
#

got it

#

ima try that

meager chasm
#
users[author_id] = {"Wallet": 0, "Bank": 0}
``` and u can do both like that
dense merlin
#

ok ty

#

KeyError: 'Wallet'

#

What do I do with that Key Error

meager chasm
#

full error pls

#

and code that caused it

dense merlin
#

nvm actually

#

i think i got it

#

wait no i dont

#

ok so the traceback:

#

Traceback (most recent call last):
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 62, in balance
wallet_amt = users[author]['Wallet']
KeyError: 'Wallet'

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

Traceback (most recent call last):
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'bal' raised an exception: KeyError: 'Wallet'

#

and the lines

#

wallet_amt = users[author]['Wallet']
bank_amt = users[author]['Bank']

meager chasm
#

ok so users[author] is a dict which doesnt have Wallet key in it

dense merlin
#

ok

meager chasm
#

so you can add Wallet key to that dict or write some code to handle the case where the dict does not have Wallet key (using try-except or if statments)

dense merlin
#

if i used the code you sent above, than shouldn't the key exisit

meager chasm
#

yes, but are u using it back to back

#

!e ```py
users = {}
users["0"] = {"Wallet": 0, "Bank": 0}

author = "0"
print(users[author]["Wallet"])

unkempt canyonBOT
#

@meager chasm :white_check_mark: Your 3.11 eval job has completed with return code 0.

0
dense merlin
#

If thats basically what I a doing, sgouldn;t my code work>

meager chasm
#

so thats probably not what ur doing

slate swan
dense merlin
#

File "main.py", line 65, in balance
users_name = await client.get_user(author)
TypeError: object NoneType can't be used in 'await' expression

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

Traceback (most recent call last):
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/uNomics/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'bal' raised an exception: TypeError: object NoneType can't be used in 'await' expression

meager chasm
#

u dont await it

dense merlin
#

oh k

slate swan
#

get_user should not be awaited, and its returning nOne for you for some reason lol

meager chasm
#

and if get_user is returning None then author is not valid id or it not in the cache

#

if ur sure its valid id then you can try with fetch_user

#

make sure the id is an int

dense merlin
#

tysm

meager chasm
#

nobody cares

ember nest
#

Because I tried a lot but it is still not working

slate swan
#

yep i can do that for you, will just take a few time cuz im not home rn

ember nest
#

Alright

feral frost
#

hello guys

#

i have question

ember nest
feral frost
#

what should i do if i get this error discord.app_commands.errors.CommandInvokeError: Command 'test' raised an exception: TypeError: 'NoneType' object is not subscriptable

#

i created this py elif TypeError: await interaction.response.send_message(content="This user does not have an account yet!") return but now this wont get printed ```py
cursor.execute(f"SELECT name FROM profile WHERE id = {user.id}")
nameB = cursor.fetchone()

    cursor.execute(f"SELECT age FROM profile WHERE id = {user.id}")
    ageB = cursor.fetchone()

    cursor.execute(f"SELECT region FROM profile WHERE id = {user.id}")
    regionB = cursor.fetchone()

    cursor.execute(f"SELECT interest FROM profile WHERE id = {user.id}")
    interestB = cursor.fetchone()

    cursor.execute(f"SELECT about FROM profile WHERE id = {user.id}")
    aboutB = cursor.fetchone()

    embed = discord.Embed(title=f"{user.name}'s profile:", color=color)
    embed.add_field(name="Name:", value=nameB[0], inline=True)
    embed.add_field(name="Age:", value=ageB[0], inline=True)
    embed.add_field(name="From:", value=regionB[0], inline=True)
    embed.add_field(name="Interests:", value=interestB[0], inline=False)
    embed.add_field(name="About me:", value=aboutB[0], inline=False)
    
    embed.set_thumbnail(url=user.display_avatar)

    await interaction.response.send_message(content="Works", embed=embed)```
slate swan
unkempt canyonBOT
#

SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also
โ€ข Python sqlite3 docs - How to use placeholders to bind values in SQL queries
โ€ข PEP-249 - A specification of how database libraries in Python should work

slate swan
#

also maybe use aiosqlite instead

delicate pilot
#

๐Ÿค”

#

@cloud dawn

slate swan
#

Who ping :(

delicate pilot
#

@deep sorrel

cloud dawn
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, 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

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

deep sorrel
delicate pilot
delicate pilot
sick birch
#

howdydoo

deep sorrel
sick birch
#

doing excellent thanks

severe mural
#

Xithu hello!

#

@shrewd fjord sorry, explain there no solution message

fading marlin
#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
severe mural
#

but, no solution

#

example /suggest message: hello

fading marlin
#

original_response doesn't need a message, it fetches the message

severe mural
#

and later said: im = await interaction.original_response('Do you want upload image?, or say "N" to skip')

#

Before old: im = await interaction.send('Do you want upload image?, or say "N" to skip')

#

i see

fading marlin
#

you're probably looking for interaction.response.send, or a modal

severe mural
#

maybe try moment idea.

#

@fading marlin

#

solution ok - and error again

fading marlin
#

send the traceback

severe mural
#

error look

#

await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")

#

Ah is original response no?

fading marlin
#

you have to replace that one with a followup, or edit the original message

severe mural
severe mural
#

await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")
message2=await interaction.original_response()

fading marlin
#

you're still responding twice, you can't do that

severe mural
#

followup

#

no remember lol.

fading marlin
#

!d discord.Interaction.followup

unkempt canyonBOT
fading marlin
#

it's a webhook

severe mural
#

ah yes.

severe mural
#

there last "await message2.delete(delay=30)"

#

@fading marlin Ok

#

there is is correct: message2 = await interaction.original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>") if is_cancelleds == True: return await message2.delete(delay=30)

#

Maybe try?

fading marlin
#

use a followup if you want to send another message after a response

severe mural
#

same "Interaction.followup"?

#

message2 = await interaction.Interaction.followup(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")

fading marlin
#

no, Interaction is the class that has an instance property followup, interaction is an instance of Interaction

severe mural
#

Hmmm

fading marlin
#

interaction.followup...

#

that returns a webhook

#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks") and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks "discord.ForumChannel.webhooks"). The ones received by the library will automatically be bound using the libraryโ€™s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
fading marlin
#

webhooks have a send method

severe mural
#

yes but no is Webhook

#

only message.

fading marlin
#

what?

delicate pilot
#

๐Ÿค”

#

how i can fix

severe mural
delicate pilot
fading marlin
severe mural
delicate pilot
#

and what

fading marlin
#

congratulations, you've installed dpy

delicate pilot
#

thanks bro

severe mural
#

@delicate pilot already?

#

restart visual studio (but you save code)

delicate pilot
severe mural
#

and error "delete"?

severe mural
fading marlin
#

send_message doesn't return anything

severe mural
fading marlin
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.
severe mural
severe mural
#

read image

fading marlin
#

original_response isn't the same as send_message

severe mural
#

example same original_response next original_response

fading marlin
#

if you want to delete a message after a certain amount of time, see the delete_after kwarg in send_message

severe mural
#

first: send_message -> second original_response three original_response?

severe mural
#

moment ok check remember

fading marlin
#

what?

severe mural
#

found: await ctx.send(embed=embed, delete_after=5.0)

#

i see .

delicate pilot
severe mural
#

@fading marlin await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}> delete_after=5.0")

#

correct?

fading marlin
severe mural
#

await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>, delete_after=5.0") think bad

#

error: discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: TypeError: send_message() got an unexpected keyword argument 'delete_after'

#

No solution FACEPALM

fading marlin
#

update your dpy

severe mural
#

?

#

@shrewd fjord you online lol.

severe mural
shrewd fjord
#

Me watching fifa

#

Busy

severe mural
# shrewd fjord Why " is wrapping dlt after

is there await interaction.response.send_message(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>", delete_after=5.0)

fading marlin
fading marlin
#

yes

severe mural
#

ya have actual current.

#

...

fading marlin
#

apparently you don't

shrewd fjord
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.
severe mural
fading marlin
#

original_response doesn't take any params, and you have to update your dpy

fading marlin
#

???

delicate pilot
#

Can anyone tell me what's the problem here

fading marlin
#

error?

delicate pilot
fading marlin
#

!intents - you don't have the message content intent enabled in the dev portal

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, 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

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

delicate pilot
#

I can change this or not

fading marlin
#

leave that as-is

delicate pilot
#

bot

#

to client

fading marlin
#

sure

#

but you also have to rename all other instances of client to bot

delicate pilot
fading marlin
#

reset your token

delicate pilot
#

what

#

bro

#

@fading marlin

fading marlin
#

you're leaking your token

#

๐Ÿคฆ don't leak your token, it can cause serious damage

#

it should've been invalidated for you now

cold sonnet
#

update

#

argentina won

shrewd fjord
delicate pilot
#

๐Ÿค”

#

@fading marlin

fading marlin
#

I've already told you how to fix your issue, and you're leaking your token again

slate swan
#

literally read the last 2 lines of the error

delicate pilot
feral frost
#

so i renamed a slash command and its not showing up ? how long can it take to show up ?

fading marlin
#

sync

feral frost
fading marlin
#

sync your command tree

feral frost
#

how ?

fading marlin
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
fading marlin
#

bot.tree.sync or whatever

feral frost
#

ah ok

full marten
unkempt canyonBOT
full marten
#

Or has another way for disable all buttons?

sick birch
#

you just loop through discord.ui.View.children and .disable=True all of them

full marten
#

Could you send me an example? @sick birch

sick birch
#
for child in <instance>.children:
  ... # disable `child` here
full marten
#

Or use an instance of the class

sick birch
#

sure you can create a disable_all method in your ui.View subclass if you want

sick birch
#

of course

#
class MyView(discord.ui.View):
  def __init__(...):
    ...
  def disable_all(...):
    for child in self.children:
      child.disabled = True
full marten
#
    def disable_all(self):
        for child in self.children:
            child.disabled = True
slate swan
#

you have to update the view again afterwards for it to visually update.

full marten
#

"Interaction failed", so it says

full marten
#

I didn't understand

sick birch
#

Resend the view basically

slate swan
# full marten what?

after you set button.disabled to true, you have to edit your message containing the view and pass something like view=self

sick birch
#

Or edit your original message with the new view (self)

#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

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

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
slate swan
full marten
#

I trying it later

drifting arrow
#

Is it possible to do guild.get_member(id) but for multiple users at once?

memberlist = [1,2,3,4,5]
member_id_list = guild.get_member(memberlist)
fading marlin
#

no, you have to get each member independently

drifting arrow
#

gaaaaah

#

ty.

sick birch
# drifting arrow gaaaaah

.get_member is O(1) so it's about as fast as it gets :)
Don't worry about performance bottleneck there

#

fetch_member is another story

sick birch
outer violet
#

Im just checking if my code is right but would the or be right in this? {cmd.signature.replace('=None' or '=new role', '')}

fading marlin
#

"=None" will always evaluate to True, so you'll always get cmd.signature.replace("=None", "")

outer violet
#

Ohh

#

What if I wanted to add more than just the โ€œ=Noneโ€

fading marlin
#

you'd have multiple .replaces

outer violet
#

Ohhh

#

I see ty for the help

fading marlin
#

you're welcome

fading marlin
#

!d discord.Client.get_guild

unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
fading marlin
#

you need the full namespace

#

you're using a class when you should be using an instance

#

get_guild isn't a coroutine either

drifting anvil
#

have never made a discord bot, but im just straight going for it

#

wish me luck :)

torn sail
#

Good luck

slate swan
#

Best of luck!

slate swan
#
@app_commands.command(name = "download", description="Download Files")

    async def download(self, interaction: discord.Interaction, name:str) -> None:

How do I make name:str optional?

#

i keep gettng this error when i run my bot Traceback (most recent call last): File "c:\Users\jonah\Downloads\Dev\turtle_1.py", line 51, in <module> client.run(os.environ['Bot token']) ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen os>", line 678, in __getitem__ KeyError: 'Bots token' Inside of "Bots token" is the actual token jus not gonna keep the token there

shrewd fjord
slate swan
#

aii

#

worked, thank you

green schooner
#

Hey, any idea on how to use this Apps feature when you click on messages or documentation on it?

naive briar
#

Context menus

green schooner
#

Thx

fast musk
#

Hmm doing something silly wrong and not sure why. In a app command, I send a response with a view that has a dropdown through the decorator. In the dropdown callback, it tries to call Interaction.edit_original_response() but I get NotFound and invalid webhook. Why?

naive briar
#

That method is used to edit the interaction's response message

#

You need to send a response message to use that method

#

(I think ducky_regal)

fast musk
#

Oh god I'm thinking of InteractionResponse.edit_message

#

lol. Thank you

slate swan
#
@client.event
async def on_ready():
  async with aiosqlite.connect("main.db") as db:
    async with db.cursor() as cursor:
      await cursor.execute('CREATE TABLE IF NOT EXISTS users (prefix STRING, id INTEGER, ad STRING, guild INTEGER, welcomechannel INTEGER, adchannel INTEGER, welcomemessage STRING, leavemessage STRING, announcechannel INTEGER, addelete)')
  await db.commit()  
  print(f"logged in as {client.user}")
  await status()
#
Traceback (most recent call last):
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 34, in on_ready
    await db.commit()
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 162, in commit
    await self._execute(self._conn.commit)
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 67, in _conn
    raise ValueError("no active connection")
ValueError: no active connection
naive briar
#

Your db variable was closed before you're trying to commit

#

Move it 1 indent up

slate swan
#

ok thank you

#
async def get_prefix(client, message):
  async with aiosqlite.connect("main.db") as db:
    async with db.cursor() as cursor:
      await cursor.execute('SELECT prefix FROM users WHERE guild = ?', (message.guild.id,))
      prefix = cursor.fetchone()
      if prefix:
        prefix = prefix[0]
      else:
        prefix = "*" #return default prefix if guild not saved in database.
    db.close()
    return prefix
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1394, in on_message
    await self.process_commands(message)
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1389, in process_commands
    ctx = await self.get_context(message)
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1288, in get_context
    prefix = await self.get_prefix(origin)
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1195, in get_prefix
    ret = await discord.utils.maybe_coroutine(prefix, self, message)  # type: ignore
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/utils.py", line 662, in maybe_coroutine
    return await value
  File "main.py", line 15, in get_prefix
    prefix = prefix[0]
TypeError: 'coroutine' object is not subscriptable
/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/client.py:416: RuntimeWarning: coroutine 'Cursor.fetchone' was never awaited
  pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
naive briar
#

Await fetchone

slate swan
#
          await cursor.execute("UPDATE users SET prefix = ? WHERE guild = ?", (text, ctx.guild.id,))
          old = await cursor.fetchone()
          pr = discord.Embed(title='prefix changed!')
          pr.add_field(name='Old Prefix:', value=old[0])
#
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 87, in setprefix
    pr.add_field(name='Old Prefix:', value=old[0])
TypeError: 'NoneType' object is not subscriptable

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

Traceback (most recent call last):
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/idk-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeErr
or(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable
shrewd fjord
#

i think it doesnt returns list

#

idk what db u using tho lol

hushed galleon
slate swan
#

anyone know why my unban command doesnt work? @client.command() async def unban(ctx, user: discord.User): await ctx.guild.unban(user) await ctx.send(f'{user} has been unbanned from the server.')

green schooner
#

Hey I am trying to get a users avatar using message.author.avatar_url down here in the embed but for some reason I get this error:
AttributeError: 'User' object has no attribute 'avatar_url' and I can't figure out how to fix it :/

My code:

# Trigger when bot gets DMed
@client.listen()
async def on_message(message):
    if message.channel.type == discord.ChannelType.private: # Check if the message is DM
        if message.author == client.user:
            pass
        else:
            channel = client.get_channel(CHANNEL_ID) # Channel to send DMs in
            print(f"[DM] Got a DM from {message.author.display_name}#{message.author.discriminator}")
            # Send the message in the channel
            embed = discord.Embed(description=message.content, color=0xffffff)
            embed.set_author(name=f"{message.author.display_name}#{message.author.discriminator} ({message.author.id})", icon_url=message.author.avatar_url)
            embed.set_footer(text="Received by DM")
            await channel.send(embed=embed)
upbeat otter
#

and better use display_avatar instead of avatar since avatar could return None in case of a discord default avatar

grand hazel
#

any idea how to like set chanel in guild for something?
like /set-log #channel
and put it in a json database

upbeat otter
#

don't use a json file really

grand hazel
upbeat otter
grand hazel
upbeat otter
#

csv is also not the best

grand hazel
green schooner
upbeat otter
#

yeah

green schooner
#

Oki!

grand hazel
upbeat otter
grand hazel
#

ok

green schooner
#

Noted

latent veldt
#

I have forked a project from GitHub how to install it's dependencies from poetry.lock file?

bitter perch
latent veldt
bitter perch
#

that is what it does yes

latent veldt
#

But how can I use it in current project?.

bitter perch
#

assuming you're in the directory you can use poetry shell to spawn a subprocess that sources the venv

slate swan
#

This has probably been asked a lot but i cant find anything on it anyone know if there is a way to change a discord bots avatar from a URL?

latent veldt
#

But not using dependencies in current directory

#

Now what to do?

bitter perch
bitter perch
latent veldt
#

?

bitter perch
#

you use it like you normally would?

#

I recommend you read the Python documentation on virtual environments.

slate swan
#

i am using discord.py but im very new so im ngl u have 0 clue what kwarg is, I tried using

response = requests.get(URL)
avatar = response.content
await client.user.edit(avatar=avatar)

but that just resulted in the bots avatar not changing and not throwing any errors

latent veldt
bitter perch
bitter perch
slate swan
#

like

with open('name.png', 'wb') as f:
  f.write(avatar)
f.close()

?

bitter perch
#

no. you need to read the bytes of the response

#

you'll want the .content attribute

slate swan
#

how would i do that if you dont mind me asking? im extremally new just been using google to try and figure everything out lol

slate swan
naive briar
#

There's no point getting a response and not using it

#

!d requests.Response.content

unkempt canyonBOT
slate swan
#

I tried running

response = requests.get('https://static.wikia.nocookie.net/marvel_dc/images/f/f1/Raven_Earth-Teen_Titans_002.jpg/revision/latest/scale-to-width-down/350?cb=20080424010459')
with open(response.content, 'rb') as f:
  read_response = f.read(response.content)
  await client.user.edit(avatar=read_response)
f.close()

and i got the error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byteโ†[0m... Am i on the right track?

naive briar
#

Why

#

It's just

await client.user.edit(avatar=response.content)
#

!d discord.ClientUser.edit

unkempt canyonBOT
#

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

Edits the current profile of the client.

Note

To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.11)") must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.11)") is given through the use of `fp.read()`.

The only image formats supported for uploading is JPEG and PNG.

Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
slate swan
#

thank you so much

#

omg im so stupid this was the first thing i did earlier but rather than grabbing the user's avatar that i wanted it was grabbing its own so it never actually changed the avatar

severe mural
#

error "discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: TypeError: original_response() takes 1 positional argument but 2 were given"

#

await interaction.original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")

#

First: im = await interaction.response.send_message('Do you want upload image?, or say **"N"** to skip') - Second: await interaction.original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")

naive briar
#

Interaction.original_response do not take arguments

#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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

Fetches the original interaction response message associated with the interaction.

If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message "discord.InteractionResponse.send_message") or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer "discord.InteractionResponse.defer"), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).

Repeated calls to this will return a cached value.
severe mural
#

._.

#

hmm

#

maybe try interaction.response.send_message ?

naive briar
#

What

severe mural
#

@naive briar okay done solution.

#

and other error.

naive briar
#

What???

severe mural
#

read error?

naive briar
#

What is interaction.interaction??

severe mural
#

hmm

#

i see forget sigh CM_Hmm

#

done fix.

#

moment check.

#

look "This interaction has already been responded to before"

naive briar
#

You can't respond to the interaction twice

severe mural
naive briar
#

Don't respond to it twice?

severe mural
#

no cant 2 arguments

severe mural
#

maybe only 1

#

not 2 correct?

naive briar
severe mural
#

read there and await interaction.original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")

naive briar
#

What does that supposed to mean

severe mural
#

..

severe mural
# naive briar What does that supposed to mean

I seriously didn't understand you? Why is it mentioning user and channel? Why can't I? It has 1 and 2 arguemtns. Is that original_response?

Because how many times thousands without understanding what is it about? I read there 1 and 2 arguments as I need to "mention and channel" but I can't so I'm not good at English and my Spanish and deaf and disability

#

But what is that I give an example.

naive briar
#

You want to edit the response?

severe mural
#

yeah

naive briar
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

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

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
severe mural
#

i see.

#

error "discord.app_commands.errors.CommandInvokeError: Command 'suggest' raised an exception: TypeError: edit_original_response() takes 1 positional argument but 2 were given"

#

same 1 and 2 aruugemnt.

naive briar
#

It's keyword-only argument method

severe mural
#

i see, there you code to fix? await interaction.edit_original_response(f"{interaction.user.mention}, your suggestion has been successfully submitted! Check <#{exist_channels[1]}>")

naive briar
#

It's just edit_original_response(content=...) ๐Ÿคท

severe mural
#

ahh

#

ya remember content=

#

No idea much sigh.

#

"content (Optional[str]) โ€“ The content to edit the message with or None to clear it."

#

there is correct?

#

ok solution done @naive briar

#

thx

drifting arrow
#

Why isnt my bot registered my new commands?

naive briar
#

Text or slash

drifting arrow
#

slash

#

i got 19 (and 1 unsynced) command, and none are belong to the new command I just made

naive briar
#

Did you sync the command tree

drifting arrow
#
async def setup_hook(self):
        for filename in os.listdir("./cogs"):
            if filename.endswith(".py"):
                await self.load_extension(f"cogs.{filename[:-3]}")
        await bot.tree.sync()
``` this runs on startup so yes
#

I never had an issue before

naive briar
#

You have to wait a bit for the commands to show up if you sync globally

drifting arrow
#

In the past the commands would show up and update basically in real time

#

Well..

#

While I wait for the command to pop on up, wanna see the command and see if I did anything wrong?

#

I cant test it to find out :/

slate swan
#

anyone there

drifting arrow
#

No

slate swan
#

lol

#

i have a question

drifting arrow
#

Welcome to the python discordpy support helpline

#

This is a safe place.

naive briar
drifting arrow
#

We care. We love. We cherish every one of you.

slate swan
#

i am runnning a bot having moderation,ping and embed on prefixes now i want to implement them with slash commands

drifting arrow
#

No question is too stupid.

slate swan
slate swan
drifting arrow
slate swan
drifting arrow
#

You need to use app_commands

slate swan
#

all embed,moderation and ping are in cog

#

here's a nice guide for slash cmds

#

i just wat to implement them in cogs

drifting arrow
#
async example(commands.Cog):
  #init here
  
  @app_commands.command(name="test", description="test")
  async def test(self, interaction:discord.Interaction):
      await interaction.response.send_message("test complete")
slate swan
#

let me show my moderation code

naive briar
#

Lol

slate swan
#

there is lot of reading dat

drifting arrow
#

i havent seen it before ๐Ÿค”

slate swan
#

data

#
import discord
from discord.ext import commands

class Moderation(commands.Cog):

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

    @commands.Cog.listener()
    async def on__ready(self):
        print(f"{self.__class__.__name__} Cog has been loaded\n-----")

    @commands.command()
    @commands.guild_only()
    @commands.has_guild_permissions(ban_members=True)
    async def kick(self, ctx, member: discord.Member, *, reason=None):
        await ctx.guild.kick(user=member, reason=reason)
        embed = discord.Embed(title=f"{ctx.author.name} has kicked {member.name}", description=reason,color = discord.Color.random())
        await ctx.send(embed=embed)

    @commands.command()
    @commands.guild_only()
    @commands.has_guild_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        await ctx.guild.ban(user=member, reason=reason)
        embed = discord.Embed(title=f"{ctx.author.name} has banned {member.name}", description=reason,color = discord.Color.random())
        await ctx.send(embed=embed)

    @commands.command()
    @commands.guild_only()
    @commands.has_guild_permissions(ban_members=True)
    async def unban(self, ctx, member, *, reason=None):
        member = await self.client.fetch_user(int(member))
        await ctx.guild.unban(member, reason=reason)
        embed = discord.Embed(title=f"{member.name} has been Unbanned", description=reason,color = discord.Color.random())
        await ctx.send(embed=embed)

    @commands.command()
    @commands.guild_only()
    @commands.has_guild_permissions(manage_messages=True)
    async def purge(self, ctx, amount=15):
        await ctx.channel.purge(limit=amount+1)
        embed = discord.Embed(title=f"{ctx.author.name} purged: {ctx.channel.name}", description=f"{amount} messages were cleared",color = discord.Color.random())
        await ctx.send(embed=embed)


async def setup(client):
    await client.add_cog(Moderation(client))
drifting arrow
#

why would you send that

slate swan
#

how to change them so that i can use them with slash commands and prefix

#

use hybrid commands

drifting arrow
slate swan
#

change all .command() to .hybrid_command() , thats all ig

drifting arrow
#

or if u want both slash and text commands, use hybrid obviously

drifting arrow
#

AAHH WHY HAVENT MY COMMANDS BEEN ADDED TO MY SERVER?!

#

REEE

slate swan
#

its from discord import hybrid_commands Right

#

nope

slate swan
#

commands.hybrid_command()

slate swan
#

discord.ext.commands
you already have it imported

latent veldt
#
    async def process_dms(self):
        await self.bot.wait_until_ready()
        with await self.bot.redis as r:
            while True:
                req = await r.blpop("send_dm")
                uid, content = pickle.loads(req[1])
                self.bot.loop.create_task(self.bot.send_dm(uid, content))
slate swan
#

let me try now

latent veldt
#

it shows error

#

object Nonetype can't be used in await expression

#

in 3rd line

naive briar
#

What even is with await

slate swan
#
Traceback (most recent call last):
  File "/home/runner/funny-bot-4/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 1264, in logs
    file.write(f"{msg.channel.category} - {msg.channel.name}\n{msg.created_at} - {msg.author.display_name}: {msg.clean_content}\n")
AttributeError: 'File' object has no attribute 'write'

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

Traceback (most recent call last):
  File "/home/runner/funny-bot-4/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/funny-bot-4/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/funny-bot-4/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'File' object has no attribute 'write'
#

.redis is None
don't use while True loop
don't use bot.loop.create_task

#
@client.command()
async def logs(ctx):
  c = client.get_channel(1031746508980224010)
  for channel in ctx.guild.text_channels:
    fileName = f"{channel.name}.txt"
    with open(fileName, "w") as file:
      async for msg in channel.history(limit=None):
        file.write(f"{msg.channel.category} - {msg.channel.name}\n{msg.created_at} - {msg.author.display_name}: {msg.clean_content}\n")
        file = discord.File(fileName)
        await c.send(file=file)
drifting arrow
#

idk maybe im just not educated enough, but pretty sure you cant use await in a while loop like that

latent veldt
slate swan
latent veldt
#

both lines i removed

slate swan
#

thanks guys it worked

drifting arrow
#

OMG I figured out my issue

#

lol

slate swan
#

you ignored the very first point @latent veldt

latent veldt
slate swan
#

tell me

#

await client.tree.sync()do i still need to use this code

#

it was in my main file

#

yes

slate swan
slate swan
# slate swan yes

can you tel me what should i code for mute and unmute commands as well

#

I'll recommend using timeouts instead

#

!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.11)").

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

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

oh

#

how should i code that

slate swan
#

this is the moderation file

#

take a discord.Member argument in your command
and use member.timeout(until)
where until is a datetime or timedelta

tropic estuary
#

hello cnan someone help me ```py
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'append'

```py

@client.command()
async def test1(ctx):
    with open("test.json", "r") as f:
      user_ids = json.load(f)

        # Add the user's ID to the user_ids list
      user_ids.append(ctx.author.id)

        # Save the updated user ID data to the JSON file
      with open("test.json", "w") as f:
            json.dump(user_ids, f)

      await ctx.channel.send("User ID added successfully!")
#

๐Ÿ˜…

slate swan
tropic estuary
#

and how?

slate swan
#

yep

#

list(user_ids) it will make it an iterable of the keys

tropic estuary
#
user_ids = list(user_ids)
#

like this?

drifting arrow
#

why is userids a dictionary anyway?

slate swan
slate swan
drifting arrow
#

you can put lists into a json file tho

#
{
  "userids": []
}```
slate swan
#

this is a dictionary

drifting arrow
#

the variable itself is regarded as a list

#

userids is part of a dictionary but when read it'll be a list

tropic estuary
drifting arrow
#

if i was wrong this wouldnt work

tropic estuary
#

doing something

slate swan
#

how would that be useful for operations like ```py
{
"user1": 0,
"user2": 2
}

slate swan
#

learn sql or a valid json like database like mongodb

drifting arrow
tropic estuary
slate swan
drifting arrow
#

Also, a json file starts to get slow after like 100k lines or whatever

#

lemme check

#

I got a json file somewhere

tropic estuary
#

also can async def be used like normal function?

slate swan
#

nope

tropic estuary
#

hmm

drifting arrow
#

finally found the file!

slate swan
drifting arrow
#

400k lines is when you start to notice some major issues

tropic estuary
#

still works so why not.

slate swan
drifting arrow
#

i've not had an issue yet

#

and I got like 30 of these files at 400k lines

slate swan
#

is your bot been used at a high frequency?

#

2-3 commands/minute

drifting arrow
#

Oh no, these files arent actively being used ๐Ÿ˜„

slate swan
#

or something

tropic estuary
#

what does json.dump do?

#

like write the thing in the json file?

slate swan
#

yes

alpine cove
#

yes it calls the buffer's .wirte

#

so you'd need a file like object

drifting arrow
#

or if you want to output it to the console, print(json.dumps(mydict, indent=4))

tropic estuary
#

how can i exclude the bot from the users?

#

is there a way?

slate swan
#

what does this mean

alpine cove
slate swan
#

url is a positional arg @slate swan

alpine cove
#

just match the user id with your database and return if its a mtch

slate swan
tropic estuary
#

@client.event
async def on_message(message):
    # Increment the user's experience points
    user_id = str(message.author.id)
    if user_id not in levels:
        levels[user_id] = {"xp": 0, "level": 1}
    levels[user_id]["xp"] += 1

    # Check if the user has leveled up
    xp = levels[user_id]["xp"]
    level = levels[user_id]["level"]
    if xp >= 2 * level:
        levels[user_id]["level"] += 1
        await message.channel.send(f"{message.author.mention} has leveled up to level {level + 1}!")

    # Save the updated leveling data to the JSON file
    with open("levels.json", "w") as f:
        json.dump(levels, f)

alpine cove
slate swan
#

!d discord.Embed.set_thumbnail

unkempt canyonBOT
#

set_thumbnail(*, url)```
Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing `None` removes the thumbnail.
alpine cove
#

actually

#

bruh

slate swan
#

ok

slate swan
drifting arrow
#

i think there's a is bot somewhere

alpine cove
drifting arrow
#

like ctx.author.bot?

alpine cove
#

and there is no need for any string formatting anywhere

#

just pass member.avatar_url

slate swan
#

!d discord.User.bot

unkempt canyonBOT
drifting arrow
#

message.author.bot

alpine cove
#

embed.set_thumbnail(url=member.avatar.url)

drifting arrow
alpine cove
#

oh bruh I thought he wanted to exclude users

#

not bots lmao

#

misread his msg

slate swan
#

no user shall use thy bot

slate swan
slate swan
slate swan
#

avatar_url has been removed from like 1.5years

#

python 2.1

slate swan
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
slate swan
naive briar
#

You need an instance

#

Also url is a keyword-only argument

slate swan
#

can u write how u would do it

golden anvil
#

Can you edit them private messages? The ones that only show to you, with the blue background - can't remember what they're called (ephemeral or something lol) nevermind you can't

naive briar
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

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

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
golden anvil
#

"You also cannot edit the ephemeral state of a message, so ensure that your first response sets this correctly."

naive briar
#

Ephemeral state

golden anvil
#

oh shit

naive briar
#

That most likely means that you can't edit to a normal message

#

That everyone can see

rustic edge
#

Hello,

How would I go about getting a random message from a channel using / commands?

slate swan
#

how do i put emoji in embeded

latent veldt
#
    @commands.Cog.listener()
    async def on_message(self, message: discord.Message):
        if message.author.bot or message.guild is None:
            return

        ctx = await self.bot.get_context(message)

        if ctx.valid:
            return

        current = time.time()

        # Spamcheck, every one second
        if current - self.bot.cooldown_users.get(message.author.id, 0) < 1.5:
            return
        self.bot.cooldown_users[message.author.id] = current

        # Increase XP on selected pokemon

        await self.increase_xp(message)

        # Increment guild activity counter

        if not message.guild:
            return

        if current - self.bot.cooldown_guilds.get(message.guild.id, 0) < 1:
            return

        self.bot.cooldown_guilds[message.guild.id] = current
        self.bot.guild_counter[message.guild.id] = self.bot.guild_counter.get(message.guild.id, 0) + 1

        spawn_threshold = 8 if message.guild.id == 793691412864434226 else 24

        if self.bot.guild_counter[message.guild.id] >= spawn_threshold:
            self.bot.guild_counter[message.guild.id] = 0

            guild = await self.bot.mongo.fetch_guild(message.guild)

            if len(guild.channels) > 0:
                channel = message.guild.get_channel_or_thread(random.choice(guild.channels))
            else:
                channel = message.channel

            if channel is None:
                return

            self.bot.loop.create_task(self.spawn_pokemon(channel))
#

getting error

#

Ignoring Exception on_message

slate swan
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.11)") 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") to do this.

Examples

Usage...
latent veldt
#

any help?

alpine cove
slate swan
#

yo, how would I make a command accept a string as a variable without having to do quotes

#
@bot.command()
async def echo(ctx, message: str):
  await ctx.send(message)
#

this doesnt work for me and i would've thought its this

upbeat otter
slate swan
#

oh ty ๐Ÿ™

slate swan
slate swan
#

there's some parts of embeds where that won't work

slate swan
shy haven
#

im trying to make my first discord bot at the moment
Any ideas on why this is not working?

@client.command
async def ping(ctx):
  await ctx.send(f'Pong! {round(client.latency * 1000)}ms')```
naive briar
#

Put two parentheses behind the @client.command like @client.command()

shy haven
#

ok ty

#
@client.command()
async def ping(ctx):
  await ctx.send(f'Pong! {round(client.latency * 1000)}ms')``` still doesnt work
#

bot doesnt send anything

#
import discord
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

bot = discord.Client()

@bot.event
async def on_ready():
  print('Bot Online!')

@client.command()
async def ping(ctx):
  await ctx.send(f'Pong! {round(client.latency * 1000)}ms')


bot.run('removed for sending purposes')```
vale wing
shy haven
#

ok

vale wing
#

!intents also this

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, 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

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

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

slate swan
#
Traceback (most recent call last):
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 96, in <module>
    bot.load_extension(f"cogs.{fn[:-3]}")
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 888, in load_extension
    self._load_from_module_spec(spec, name, extras=extras)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 769, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
nextcord.ext.commands.errors.ExtensionFailed: Extension 'cogs.cog' raised an error: ImportError: cannot import name 'Enum' from 'discord' (unknown location)```
supple ridge
#

is there a way one can update a json key for example

i have a json key that is
owner = [1234]
now i want to add one more id in it that's 5678 so that it becomes

owner = [1234,5678]

naive briar
#

My my

#

!e

ml = [1234]
print(ml)

ml.append(5678)
print(ml)
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | [1234]
002 | [1234, 5678]
supple ridge
#

:0 wow ty

slate swan
rare echo