#discord-bots

1 messages Β· Page 184 of 1

naive briar
#

!d bool

unkempt canyonBOT
#

class bool(x=False)```
Return a Boolean value, i.e. one of `True` or `False`. *x* is converted using the standard [truth testing procedure](https://docs.python.org/3/library/stdtypes.html#truth). If *x* is false or omitted, this returns `False`; otherwise, it returns `True`. The [`bool`](https://docs.python.org/3/library/functions.html#bool "bool") class is a subclass of [`int`](https://docs.python.org/3/library/functions.html#int "int") (see [Numeric Types β€” int, float, complex](https://docs.python.org/3/library/stdtypes.html#typesnumeric)). It cannot be subclassed further. Its only instances are `False` and `True` (see [Boolean Values](https://docs.python.org/3/library/stdtypes.html#bltin-boolean-values)).

Changed in version 3.7: *x* is now a positional-only parameter.
naive briar
#

Or using choices

static holly
#

hi, my code is correct, but i want the mention is mentionned
how to? please

  @commands.command(pass_context=True)
    async def hug(self, ctx, *, member_mention:discord.Member=None):
        user= ctx.author.mention
        await ctx.send (f"{user} say hi to {member_mention}")
slate swan
#

I tried doing setting:bool

naive briar
#

!d discord.Member.mention

unkempt canyonBOT
static holly
slate swan
#

Do you want it to be random or under a certain circumstance they get pinged

static holly
#

if mention== true > answer 1
else: answer 2

is correct?

slate swan
#

try something like this:

@commands.command(pass_context=True)
async def hug(self, ctx, *, member_mention:discord.Member=None)
  if member_mention == None:
    pass # if none it'll go here
  else:
    pass # if you ping someone it'll go here

Think this will work?

static holly
#

pass? what is this?

naive briar
#

Nothing

slate swan
#

replace pass with code

naive briar
#

!d pass

unkempt canyonBOT
#

7.4. The pass statement


pass_stmt ::=  "pass"
``` [`pass`](https://docs.python.org/3/reference/simple_stmts.html#pass) is a null operation β€” when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:

```py
def f(arg): pass    # a function that does nothing (yet)

class C: pass       # a class with no methods (yet)
static holly
#

okay!

slate swan
#

you put pass in spots you don't need code to run

static holly
#

okay, thanks πŸ™‚

slate swan
#

I use it if I don't want code in that spot yet so it doesn't error lol

slate swan
static holly
slate swan
#

somethin like that

left dew
#

anyone know is there is something i can use like active_developer to flag if the user has that badge?

autumn totem
#

Hello I wanted to host my bot and I always get this error can someone help?

import discord
from discord.ext import commands
import discord.ui
import os
from dotenv import load_dotenv

load_dotenv()


intents = discord.Intents.all()

bot = commands.Bot(command_prefix='.', intents=intents, help_command=None)
client = discord.Client()

@bot.event
async def on_ready():
  print('System rebooted.')
  bot.add_view(Verification())

class Verification(discord.ui.View):
  def __init__(self):
    super().__init__(timeout = None)
  @discord.ui.button(label="βœ…",custom_id = "Verify",style = discord.ButtonStyle.success)
  async def verify(self, button, interaction):
    role = 1066356340789870707
    user = interaction.user
    if not any(role == _role .id for _role in user.roles):
      await user.add_roles(user.guild.get_role(role))
      await user.send("πŸ‡¬πŸ‡§ You have been verified!\nπŸ‡©πŸ‡ͺ Du wurdest verifiziert!")

@bot.command()
async def verify(ctx):
  embed = discord.Embed(title = "Verification", description = "Click below to get verified!\nKlicken unten, um dich verifizieren zu lassen! ")
  await ctx.send(embed = embed, view = Verification())

bot.run(os.environ.get("TOKEN"))

shrewd apex
#

less go my bot got verified pikachu_sip

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.

autumn totem
#

or doesnt that matter?

shrewd apex
naive briar
#

It won't be there if there's nothing wrong

autumn totem
#

yh but thats true

#

I aint long into coding bots

#

since yesterday

autumn totem
austere prairie
#

yeah, you only need one (preferably commands.Bot)

autumn totem
#

Alright thanks

shrewd apex
#

πŸ’€ we need a warning note for chatgpt with discord bots

autumn totem
#

Yeah haha

austere prairie
#

we already had an announcement for chatgpt in general

autumn totem
#

❀️

austere prairie
#

πŸ‘

sly fog
#

How do I reformat the default help command

#

like i wanna make it an embed for example

#

do i have to rewrite the whole help command?

#

or is there a different way

obtuse iris
#

!or

austere prairie
#

I haven't used it before though

sly fog
#

oh ok

#

thx

sly fog
golden portal
#

!customhelp

unkempt canyonBOT
#

Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

ebon island
#

Using wavelink to play static local files, what is the most efficient way to accomplish a 24/7 music playlist? I know wavelink has a queue feature but is it more efficient to create a large queue on the order of thousands or to programmatically load the instrumentals one at a time and play them on demand or some combination of the two like for example having a queue of a given length and keeping it populated? I'm curious what the best design pattern is for handling such things for a locally sourced 24/7 music player. Thanks!

#

I'm curious what would be the better solution in terms of memory efficiency and scalability

slate swan
#
import discord
from discord import app_commands
from discord.ext import commands
import coc
import requests

key = "my_key"

url = "https://api.clashofclans.com"

headers = {
"Accept" : "application/json"
"Authorization" : "Bearer %s" % key
}

response = requests.request("GET", url, headers=headers)

client = commands.Bot(command_prefix=">", intents=discord.Intents.all())

@client.event
async def on_ready():
    print('Bot online')
    
@client.command()
async def player(ctx, tag):
    player = await client.get_player("tag")
    await ctx.send(f"{player.name} has {player.trophies} trophies!")
    
client.run("token")```
#

i have a syntax error

#

my trying to use API for the first time

#

i followed a tutorial

shadow wraith
#

you're missing a ,

slate swan
#

after what?

#

json", ?

shadow wraith
#

after "application/json"

slate swan
#

okay

shadow wraith
#

why are you using the clash of clans api though 🀣

ebon island
#

You need a comma after the application Json on the first line for starters

#

Additionally, you should get in the habit of using F strings because they are great, very easy to use

slate swan
ebon island
#

example_fstring = f'Bearer {key}'

quick gust
#

I believe they are aware of how to use f strings as they have used it in their command

ebon island
#

Ah, I didn't look at that code but anytime I see old formatting methods I assume it is most likely done through lack of knowledge of f-strings and this is a teaching moment for better practices since many new python coders follow tutorials and such and do not know the distinction

ebon island
#

I just literally want to know which is considered the best practice for static locally sourced files, I have all search mechanisms disabled and the bot will randomly choose tracks to add based on the parameters indicated, curious if it would be better to create a queue of some length and if so what length or if it would be better to play each instrumental On Demand upon completion

naive briar
#

I would just use queues

shut axle
#

!cogs

#

!d

unkempt canyonBOT
ebon island
#

Sounds good, I will try that, is it going to be an issue at scale say if I have many servers each with hundreds and potentially more than a thousand instrumentals All In queues individually assigned to each server?

naive briar
#

I mean

#

I would use a database then

#

If it's small or private queues are enough

ebon island
#

What purpose would the database serve? All of the files are local so I can just index them and I will either way have to execute some sort of logic to either Play On Demand or create a q which will enable the 24/7 music player Behavior

naive briar
#

Idk, if you have a ton of ram in your machine then I guess

#

I just feels like store tens of thousands of objects in the ram would be too heavy

#

If your bot are really that big

#

Or I'm just overreacting, who knows

ebon island
#

Fair, I will definitely give it more thought and eventually I am definitely going to have an API serving this stuff with a database so I will address that eventually but at least theoretically all it is is file paths because only when the instrumentals are played is the file actually accessed otherwise it is just a whole bunch of strings or lightweight objects

#

Appreciate the response!

vale wing
rapid knoll
#

how do you timeout a member

naive briar
#

!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").
rapid knoll
simple plume
#

So I have this code that when a user sends any kind of message the bot must reply, but the bot isn't doing anything xd

rapid knoll
simple plume
rapid knoll
simple plume
rapid knoll
# simple plume Still not working
@client.event
async def on_message(message):
    if message.author == bot.user:
        return
    await message.channel.send("This is a response")

That should work

vale wing
#

Use listen() instead of event

pallid meadow
#

assuming they are doing this in a singular file

vale wing
naive briar
#

Use listen

#

🀣

#

Just ask your questions

vale wing
primal token
#

Why are you guys attacking the poor lad

pallid meadow
#

or I just subclass my bot

vale wing
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
pallid meadow
#

okay...

vale wing
#

Cog.listener() is a different thing

primal token
#

listeners are better overall, you avoid many abstraction issues

primal token
vale wing
#

Yes

pallid meadow
vale wing
#

I never said it's not a listener

pallid meadow
#

you said it's a different thing which implies that

#

but okay whatever

naive briar
#

They're different in where you use them

#

But serves same purpose

primal token
#

You want to make new lines?

#

!e

print("Hello\nWorld!")
unkempt canyonBOT
#

@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Hello
002 | World!
naive briar
#

Or triple quotes

primal token
#

what was its name again

#

!d discord.discord.ext.commands.Author

unkempt canyonBOT
#

discord.ext.commands.Author```
A default [`Parameter`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Parameter "discord.ext.commands.Parameter") which returns the [`author`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.author "discord.ext.commands.Context.author") for this context.

New in version 2.0.
primal token
#

lovely dir

primal token
# unkempt canyon

@slate swan use this as your default value in your member argument, you can save yourself the task of checking the value of member with

if member == None: 
        member = ctx.author
upper root
#

Hello guys anyone familiar with nextcord? I have recently switched to it and I created a cog but I cannot make the command show up

#

any idea why?

naive briar
#

Easy, it's nextcord

pallid meadow
#

code?

#

...

#

that's not very helpful

upper root
#

that is my main.py

import nextcord
from nextcord import Interaction
from nextcord.ext import commands
import os

from dateutil import parser
import random
from const import *
from utils import *

client = commands.Bot(command_prefix="!", intents=nextcord.Intents.all())


@client.event
async def on_ready():
    print("Bot is load")


initial_extensions = []
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        initial_extensions.append("cogs." + filename[:-3])

if __name__ == '__main__':
    for extension in initial_extensions:
        client.load_extension(extension)

client.run(BOT_TOKEN)
import nextcord
from nextcord.ext import commands
from nextcord import Interaction
from dateutil import parser
from discord.ext import commands
import random


class solebox(commands.Cog):
    def __init__(self, client):
        self.client = client

        @nextcord.slash_command(name="test", description="Test")
        async def test(self, itr: Interaction):
            await itr.response.send_message("Hello", ephemeral=True)


def setup(client):
    client.add_cog(solebox(client))
pallid meadow
primal token
#

πŸ‘€

upper root
#

if anyone has an idea im willing to take haha

vocal plover
# naive briar Easy, it's nextcord

Consider providing people with useful help rather than just blaming a library without reason, or just don't provide help. It's not useful to just start wars between libs

naive briar
#

Can't always deny the facts

vocal plover
#

Well the facts here are that you're pointlessly trying to create library drama in a channel where people ask for help, so this isn't the place.

vocal plover
#

the command is indented too far in your cog class, it should be at the same level as __init__, not within that function

slate swan
#

Guys I took a data base from replit for music bot and I add some stuff the bot is online but it doesn't respond to my commands
NB: am just a beginner

vocal plover
#

in the second code block,

class MyCog:...
  def __init__(): ...
  
  @nextcord.slash_command()
  ...
```it should be indented like that
#

currently you have the slash command nexted within the init function, but it needs to be on the class, not in the function

slate swan
#

@vocal plover

vocal plover
#

I don't help with music bots since they generally violate Discord's and YouTube's terms of service

simple plume
vale wing
fiery rain
#

Could anyone help me import discord slash command into my code? Got no idea how to do it, haven’t coded in 2 years now.

shrewd barn
#

how to edit an embed respond for slash command?

#

or how to edit an embed

upper root
#

Hello guys so I recently switched all my commands into cogs and I had before errors handlers that if the person using the commands is missing a role it will answer with a message "Only admins are allowed to use this command!"
although now someone told me to create a cog with this error

import nextcord
from nextcord.ext import commands, application_checks
from nextcord import Interaction
from dateutil import parser
from nextcord.ext import commands


class error(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_error(self, itr: Interaction, error):
        print("an error is being raised")
        if isinstance(error, nextcord.ext.commands.MissingAnyRole): await itr.response.send_message(
            "Only admins are allowed to use this command!")


def setup(client):
    client.add_cog(error(client))

Any idea on how to do it? what should i fix? because the bot is not sending the error

vale wing
#

Not sure if nextcord has separate events for slash commands

tough lance
#

Hi, I'm using disnake and my bot just disconnects after a few hours of runtime. But the python script keeps running

#

I wanted to know if you can kill the script in anyway...

upper root
#

but I still do not get any message

#

Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x0000020515B0BF10>:
I get this idk why

vale wing
#

Why tf they put it into checks πŸ’€

#

@upper root error handler should raise unknown exceptions

if isinstance(err, SomeError):
    ...
else:
    raise err```
upper root
vale wing
#

That was an example

#

Key part is else clause

shrewd barn
#

how can i get the id of user launched slash command

upper root
#

Will that be possible ? And if so what should the form of the file handlingerrors look like ?. A simple @client.event

autumn totem
#

Can someone help me with this error?

one row=None>
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "/home/container/app.py", line 25, in verify
    user = interaction.user
AttributeError: 'Button' object has no attribute 'user'
#

Code:

import discord
from discord.ext import commands
import discord.ui
import os
from dotenv import load_dotenv

load_dotenv()


intents = discord.Intents.all()

bot = commands.Bot(command_prefix='.', intents=intents, help_command=None)

@bot.event
async def on_ready():
  print('System rebooted.')
  bot.add_view(Verification())

class Verification(discord.ui.View):
  def __init__(self):
    super().__init__(timeout = None)
  @discord.ui.button(label="βœ…",custom_id = "Verify",style = discord.ButtonStyle.success)
  async def verify(self, button, interaction):
    role = 1066356340789870707
    user = interaction.user
    if not any(role == _role .id for _role in user.roles):
      await user.add_roles(user.guild.get_role(role))
      await user.send("πŸ‡¬πŸ‡§ You have been verified!\nπŸ‡©πŸ‡ͺ Du wurdest verifiziert!")

@bot.command()
async def verify(ctx):
  embed = discord.Embed(title = "Verification", description = "Click below to get verified!\nKlicken unten, um dich verifizieren zu lassen! ")
  await ctx.send(embed = embed, view = Verification())

bot.run(os.environ.get("TOKEN"))
slate swan
#
await bot.get_channel(channel_premium_id).send(embed=log_embed)

Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'```
vale wing
tough lance
vale wing
#

Do you use asyncpg client or you embed API

tough lance
#

explain a bit more...

vale wing
#

Do you just make requests with it or you have API server embedded into bot

tough lance
#

I still don't get it, but the postgres server is hosted on the same server as the bot

vale wing
#

Ok then you just make requests if you don't understand what I mean

timid spade
#

how do make it so if the error is not missing permission it gets displayed in console normally

fading marlin
#

Add an else block and raise error

timid spade
#

thanks

thin oar
#

anyone else having problems with the discord servers?

#

aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected

simple plume
vale wing
#

Here

slate swan
tough lance
#
credentials1 = {"user": "user", "password": "pass", "database": "main", "host": "localhost"}
bot.conn = await asyncpg.create_pool(**credentials1, max_inactive_connection_lifetime=10)
slate swan
#

what is the disconnect message

tough lance
#

nothing?

slate swan
#

that doesn't make sense.

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

slate swan
#

you say your bot is disconnecting yet you don't see anything about a disconnect in console?

vale wing
#

Send only part that is related to your issue

tough lance
slate swan
tough lance
vale wing
#

Do you have logging set up?

tough lance
#

Ya

#

INFO

vale wing
#

Debug level?

#

Do debug level

slate swan
#

info level still provides logs on disconnect

vale wing
#

Probably will be able to catch more stuff

slate swan
#

i don't think it is being disconnected from discord. it sounds like a host issue

unkempt canyonBOT
#

Hey @thin oar!

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

simple plume
tough lance
slate swan
thin oar
slate swan
#

oh nvm lmao i see it at the bottom

vale wing
#

@simple plume you shouldn't be doing commands that way

vale wing
slate swan
#

also why are u running the client then defining bot wtf am i looking at

vale wing
slate swan
#

and ur using client and bot both lol

simple plume
thin oar
# vale wing Show full traceback

2023-01-22 20:29:12 ERROR discord.client Ignoring exception in on_message
Traceback (most recent call last):
File "/home/milan/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 980, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore[return-value] # noqa
File "/usr/lib/python3.10/asyncio/base_events.py", line 1089, in create_connection
transport, protocol = await self._create_connection_transport(
File "/usr/lib/python3.10/asyncio/base_events.py", line 1119, in _create_connection_transport
await waiter
ConnectionResetError

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

Traceback (most recent call last):
File "/home/milan/.local/lib/python3.10/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "/home/milan/develop/discord call out bot python/main.py", line 185, in on_message
await message.channel.send(f"{coin.upper()} price: {cur_price}")
File "/home/milan/.local/lib/python3.10/site-packages/discord/abc.py", line 1540, in send
data = await state.http.send_message(channel.id, params=params)
File "/home/milan/.local/lib/python3.10/site-packages/discord/http.py", line 624, in request
async with self.__session.request(method, url, **kwargs) as response:
File "/home/milan/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1141, in aenter
self._resp = await self._coro
File "/home/milan/.local/lib/python3.10/site-packages/aiohttp/client.py", line 536, in _request
conn = await self._connector.connect(
File "/home/milan/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 540, in connect
proto = await self._create_connection(req, traces, timeout)
File "/home/milan/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 901, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
File "/home/milan/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 1206, in _create_direct_connection
raise last_exc
File "/home/milan/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 1175, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
File "/home/milan/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 988, in _wrap_create_connection
raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host discord.com:443 ssl:default [None]

vale wing
#

Mac or win?

thin oar
#

win

#

ubuntu specific

vale wing
#

What

#

Windows is not ubuntu at all

thin oar
#

I am running the code on ubuntu but my pc is win

vale wing
#

Those are like completely different things

vale wing
slate swan
#

looks like ubuntu

slate swan
#

he's using WSL maybe

#

ah yea

thin oar
#

my code is working, I am running it for a few days, not a problem but now suddenly it doesn't work anymore

#

the delay is like 2 minutes

vale wing
thin oar
slate swan
#

its a connection issue, most probably because of internet availability

thin oar
#

I am using a cable

slate swan
#

!d aiohttp.ClientConnectionError

unkempt canyonBOT
#

class aiohttp.ClientConnectionError```
These exceptions related to low-level connection problems.

Derived from [`ClientError`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientError "aiohttp.ClientError")
vale wing
#

Or bad certificates

slate swan
slate swan
thin oar
#

aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected

vale wing
slate swan
#

if that's the issue installing certifi should make it work

vale wing
#

But yeah the error looks like connection issue

thin oar
vale wing
#

Does ping to anything work

thin oar
vale wing
#

ping google.com for example

thin oar
#

PING 142.250.181.238 (142.250.181.238) 56(84) bytes of data.
64 bytes from 142.250.181.238: icmp_seq=1 ttl=119 time=0.926 ms
64 bytes from 142.250.181.238: icmp_seq=2 ttl=119 time=0.372 ms
64 bytes from 142.250.181.238: icmp_seq=3 ttl=119 time=0.346 ms
64 bytes from 142.250.181.238: icmp_seq=4 ttl=119 time=0.356 ms
--- 142.250.181.238 ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 61ms
rtt min/avg/max/mdev = 0.346/0.500/0.926/0.246 ms

thin oar
vale wing
#

That's from same machine you run the bot from?

slate swan
#

instead of using the discord.py module is it possible to do this in a json format

embed2.set_image(url="attachment://image.png")```
vale wing
#

?

slate swan
#

is it possible to upload an attachment with a json format

#

i may be in the wrong chat for this

vale wing
#

You mean raw request to discord API?

slate swan
#

ye

vale wing
#

One sec

slate swan
#

thanks

static holly
#

hi, I would like to know if it is possible to resize an image in an embed? I have a list of images that is imported randomly, and I would like that no matter the image, it must be a maximum of 150px in height

unkempt canyonBOT
static holly
slate swan
#
Command raised an exception: AttributeError: 'Message' object has no attribute 'wait_for'```
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
mild lava
#

how can i add internal paramaters to a discord.py app_command? i have a decorator that constructs some custom context, and passes it to the command function along with the interaction and other args, but discord.py doesn't like extra args in my command because it expects only args that are meant to be used client-side.

example:

@app_commands.command()
@custom_deco
async def my_command(
  self,
  interaction: Interaction,
  custom_ctx: CustomCtx,
  command_arg: str
):
  pass

custom_ctx is my custom context, passed by the decorator, and command_arg is an actual argument for the client-side command

error:

discord.ext.commands.errors.ExtensionFailed: Extension 'game' raised an error: TypeError: unsupported type annotation <class 'game.GameInstance'>  # GameInstance is the custom context
#

im thinking i probably have to wrap creation of the command with a decorator, but im unsure of how to go about that

potent spear
#

why would you need an extra arg in your command in the first place?

sick birch
#

But yeah sounds like an XY problem
If you tell us what your original real problem is we can see if there are better ways to do it

potent spear
#

I feel like he just needs to set a botvariable

jovial steeple
#
import discord
import asyncio

intents = discord.Intents.all()
client = discord.Client(intents = intents)
ticket_users = {}
@client.event
async def on_message(message):
    if message.channel.type == discord.ChannelType.private and message.content.startswith("ticket"):
        user = message.author
        if user.id in ticket_users:
            await user.send("Du hast bereits ein Ticket erstellt. Bitte warte auf eine Antwort oder schließe das Ticket mit close.")
            return
        else:
            ticket_users[user.id] = True
        guild = client.get_guild(ID) # Replace GUILD_ID with the ID of the server where you want to create the channel
        channel = await guild.create_text_channel(f"ticket-{user.name}")
        await channel.send(f"{user.mention} hat ein Ticket erstellt.")
        await user.send("Dein Ticket wurde erstellt. Ein Teammitglied wird sich in KΓΌrze bei dir melden.")

        def check(m):
            return m.author == user and m.channel == channel

        while True:
                msg = await client.wait_for('message', check=check)
                if msg.attachments:
                    await user.send(msg.content, file=msg.attachments[0])
                else:
                    await user.send(msg.content)
                if msg.content.startswith == "close":
                    del ticket_users[user.id]
                    await channel.send("Ticket wurde geschlossen.")
                    await user.send("Dein Ticket wurde geschlossen.")
                    await channel.delete()
                    break
client.run("My Token")

I created a ticket system, where a user needs to dm the bot with "ticket". A ticket_channel will be created on the server and the function of all this is, that all the messages, that the user is sending to the bot, the bot sends these messages to the channel in my server. And reversed:
The problem here is that the command "ticket" is working (a new text channel has been created) if the user sends a message, the channel in the server recieves nothing

#

Can someone help me?

potent spear
#

this will make things a lot easier to maintain
there are decorators etc for commands to make sure they only work in private channels etc

#

everything till the "check" function (not included) should be a ticket command

jovial steeple
mild lava
potent spear
#

so still.. what's the extra arg for?

mild lava
#

the game instance

potent spear
#

why don't you use a database or whatever to store their progress?

mild lava
#

i just dont want to check that a game instance exists, and retrieve it, in every single command that requires the context

#

rather do it once in a wrapper

potent spear
#

ok, you did that already...

#

you can just use a botvar for that, which just checks in the db if a "game progress" between 2 user IDs in a certain guild is already established

mild lava
#

yep. it worked alright before i started migrating to slash commands. parameter handling changed and now it doesnt accept that custom parameter

potent spear
unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

potent spear
#

maybe that's what you need to keep track of your "game instances"

mild lava
#

i already keep track of my game instances using a self.games variable in the cog

potent spear
#

alright, then still, what do you pass as extra arg in your command that's sΓ³ needed?

mild lava
#

here's the decorator


class Game(Cog):
    def __init__(self, bot: Bot):
        self.bot = bot
        self.games: dict[int, GameInstance] = {}

    @staticmethod
    def game_command(func):
        @functools.wraps(func)
        async def decorator(self: "Game", interaction: Interaction, *args, **kwargs):
            if interaction.channel_id in self.games:
                await func(
                    self,
                    interaction=interaction,
                    game=self.games[interaction.channel_id],
                    *args,
                    **kwargs,
                )
            else:
                await interaction.response.send_message("No game started.", ephemeral=True)

        return decorator
potent spear
#

I would never handle that stuff in your decorator tbh

mild lava
#

the reason i wrote it was to abstract away all the game instance handling and retrieving, so i don't have to copy & paste that code into every single command that requires a game instance

potent spear
#

I'd just throw an error and let your error handler send that message

potent spear
mild lava
#

command_arg represents regular arguments that are supposed to be used client-side

teal glade
#

How do you write a function to get a random tenor gif using a query?

potent spear
teal glade
#

The first question

potent spear
potent spear
mild lava
#

im aware, i cant have both Interaction and Context, but i dont need discord.py's context, im just trying to pass arbitrary arguments into my command function while calling it. seems like i have to write some custom command creation wrapper.

potent spear
#

you don't need the custom context passed to be able to use your custom decorator

mild lava
#

is there a better way to wrap an app_command function?

potent spear
mild lava
#

my custom decorator does work, its not the issue

#

the issue is that i can't pass arbitrary arguments to my command functions without discord.py thinking the parameters are for the actual slash command

potent spear
mild lava
#

i've got a large amount of commands that require additional information to run, so rather than checking that the information exists and retrieving it in every single command, i want to be able to pass the information as an argument

#

which will be provided by a decorator

potent spear
#

which can basically prevent or do whatever with certain commands before they're executed

mild lava
#

can it pass arguments?

potent spear
#

yes, most likely
but you're still looking at this at a wrong angle... you don't need to pass arguments, you just need to get / edit them through a botvar or whatever

mild lava
#

i don't think storing the current command's game instance in a botvar would play nicely with many commands being run at the same time asynchronously.

potent spear
mild lava
#

maybe i could attach the game instance to the already existing interaction parameter

mild lava
#

& validate

potent spear
#
  • it's async
mild lava
#

takes a lot of duplicated code

#

time was never an issue

potent spear
#

duplicated code?

#

you're just editing the game progress in the db while making moves

#

I have to be able to reproduce it

mild lava
#

say i had 50 different commands. each one, at the beginning of the function, would need to do the same steps: check that a game instance exists for the channel, and get it

potent spear
#

mhm, not a problem

rare echo
mild lava
#

i have thought of that. it would require quite a bit of rewriting in my case, but its an option i will pursue if i can't get this to work

potent spear
#

you can even write a cog check in your case
=> checks a certain function for every command in a cog without having to put that decorator on top of every command in the cog

mild lava
#
  1. that seems to only work with old commands that take ctx, not interaction, and 2. it doesnt solve the issue of passing arguments to command functions. i've begun working on something, will come back if i run into more issues
slate swan
#

!d discord.app_commands.CommandTree.interaction_check

unkempt canyonBOT
#

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

A global check to determine if an [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") should be processed by the tree.

The default implementation returns True (all interactions are processed), but can be overridden if custom behaviour is desired.
spice jewel
#

still need help w this

#
msg = await spooky.wait_for("none", check=lambda x: x == ctx.author)
    if msg.content  == 'none' and ctx.author == msg.author:
        await ctx.send("no reason selected")
        await member.remove_roles(roles)
        await member.edit(nick=None)
        dynamic_timestamp = discord.utils.format_dt(datetime.now(), style="R")
        remove=discord.Embed(
            title="β €β € User Removed ✦", 
            description=f"{member.mention} has been removed", 
            color=discord.Color(0xac0101)
            )
        await ctx.send(embed=remove)
    else:
        await member.remove_roles(roles)
        await member.edit(nick=None)
        dynamic_timestamp = discord.utils.format_dt(datetime.now(), style="R")
        remove=discord.Embed(
            title="β €β € User Removed ✦", 
            description=f"{member.mention} has been removed", 
            color=discord.Color(0xac0101)
            )
        await ctx.send(embed=remove)```
#

it's still not sending anything

potent spear
spice jewel
spice jewel
potent spear
spice jewel
#

it's still not doing anything, here is the updated code:

potent spear
#

but as the docs state, with wait_for, you don't have to type the on_\_

#

have you tried debugging? or are you guessing?

spice jewel
#
    msg = await spooky.wait_for("message", check=lambda x: x == ctx.author)
    await ctx.send("no reason selected")
    await member.remove_roles(role)
    await member.edit(nick=None)
    dynamic_timestamp = discord.utils.format_dt(datetime.now(), style="R")
    remove=discord.Embed(
        title="β €β € User Removed ✦", 
        description=f"{member.mention} has been removed", 
        color=discord.Color(0xac0101)
            )
    remove.set_thumbnail(url=member.avatar)
    remove.add_field(
        name="Removed by:",
            value=f"{ctx.author.mention}"
        )
    remove.add_field(
        name="Date removed:",
        value=dynamic_timestamp,
        inline=True
        )
    remove.add_field(
        name="ID:",
        value=f"{ctx.author.id}",
        inline=False
        )
    remove.add_field(
        name="Reason:",
        value=msg,
        inline=False
        )
    await ctx.send(embed=remove)```
spice jewel
potent spear
spice jewel
sick birch
#

Run it and see ℒ️

spice jewel
potent spear
spice jewel
potent spear
#

the lambda is incorrect in your check function

#

you're copy pasting

sick birch
potent spear
#

πŸ₯„

spice jewel
#
msg = await spooky.wait_for("message", check=lambda x: x.author == ctx.author)```
sick birch
#

That's the message object

potent spear
#

good, now the rest should be a piece of cake

spice jewel
#

yep ty!

spice jewel
#

yeah for the reason, when I made the value msg

spice jewel
#

when I wanted it to be whatever the user said

#

what should I change it to?

slate swan
slate swan
#

!d discord.Message.content

unkempt canyonBOT
slate swan
#

^

spice jewel
#
    remove.add_field(
        name="Reason:",
        value=str(discord.message.content),
        inline=True
        )
    await ctx.send(embed=remove)```
potent spear
spice jewel
potent spear
#

this library has a steep learning curve, so it's more for intermediate programmers, try to grasp the basics first and you'll get projects like these done in no-time
it's GOOD you're not using youtube or whatever as a main source though, that's something to avoid

static holly
#

please, is it possible to add a variable in embed field?

unkempt canyonBOT
#

xy-problem

The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.

Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.

For more information and examples, see http://xyproblem.info/

static holly
#

because i create a help command and i want enter server.text_channels number in str method

static holly
#

len(server.text_channels) in fields in embed

#

its possible?

potent spear
#

do you just want to add an extra field to an embed?

#

which shows how many text channels there are in your current guild?

static holly
potent spear
unkempt canyonBOT
#

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

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

just add a field to the embed and pass something in the name and value arg

static holly
#

yes, but i have a error

potent spear
#

first time you're mentioning that

static holly
# potent spear just add a field to the embed and pass something in the name and value arg

look

@commands.command(pass_context=True, neme="help")
    async def help(self,ctx):
        server=ctx.guild
        nombre_channel_text=len(server.text_channels)

        embed=discord.Embed(title="infos sur le bot", description="Vous trouverez toutes les infos Γ  savoir sur moi.", color=discord.Color.brand_red)
        embed.add_field(
            name= "Nombre de salons textuels"
            value=len(nombre_channel_text))
#

"(" was not closed

#

i dont find the error

static holly
#

no just "(" was not closed

potent spear
static holly
#

πŸ˜•

#

okay, thanks

potent spear
static holly
potent spear
buoyant quartz
#

Ignoring exception in on_message Traceback (most recent call last): File "C:\Users\me\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\nextcord\client.py", line 512, in _run_event await coro(*args, **kwargs) TypeError: on_message() takes 0 positional arguments but 1 was given

#

why doesnt that work?

spice jewel
#
await ctx.send(":001callisto: **WARNING: This will remove the user entirely from the system, would you like to proceed?** :001callisto:")
msg1 = await spooky.wait_for("message", check=lambda x: x.author == ctx.author)
    if msg1.content == "y":
        await ctx.send("What is the reason for removing?")
        msg2 = await spooky.wait_for("message", check=lambda x: x.author == ctx.author)
        await member.remove_roles(defined_roles)
        await member.edit(nick=None)
        dynamic_timestamp = discord.utils.format_dt(datetime.now(), style="R")
        remove=discord.Embed(
            title=f"User Removed - {member.tag} ✦", 
            timestamp=datetime.datetime.utcnow(),
            color=discord.Color(0xac0101)
                )
        remove.add_field(
            name="User ID:",
            value=f"``{member.id}``"
                )
        remove.add_field(
            name="Reason:",
            value=msg2.content,
            inline=False
                )
        remove.set_footer(text=f'{member.id}')
        await ctx.send(embed=remove)```
#

recognises content of the first message (y) and responds correctly but for msg2 it doesn't respond with anything, does anyone know why?

naive briar
#

Just add message or msg to the event's function arguments

naive briar
buoyant quartz
spice jewel
spice jewel
vale wing
#

f"{msg}" is useless fyi, just use msg, it's already a string instance

buoyant quartz
#

nvm it was just repeating its own message

young dagger
#

Can you leave description empty in embeds?

slate swan
#

yes

mild lava
sick birch
#

Or just a regular string and split by , or some other delimiter

mild lava
#

this is the current implementation. before i migrated to slash commands the user would just mention a bunch of members and the bot would use message.mentions

sick birch
#

How many players?

mild lava
#

2 to infinity, inclusive

sick birch
#

Ah

#

Why not send a button after? users that want to play have to just click on it

mild lava
#

damn. thats smart

#

thank you

sick birch
#

no prob

young dagger
#

Should I just merge tier and rank to avoid this?

    # Create a list of ranks for team 1
    team_1_ranks = [f"{u['tier']} {u['rank']} ({u['elo_rating']})" if u['tier'] != "Unranked" else f"Unranked ({u['elo_rating']})" for u in team_1]

    # Create a list of ranks for team 2
    team_2_ranks = [f"{u['tier']} {u['rank']} ({u['elo_rating']})" if u['tier'] != "Unranked" else f"Unranked ({u['elo_rating']})" for u in team_2]```
sick birch
#

Yeah do merge that

vocal hollow
#

how to make a role in server pingable

sick birch
#

Roles are pingable by default

vocal hollow
#

no like in a channel the @ everyone is off but i still want roles to be pingable

#

i want to turn @ everyone off in every channel but allow specific roles to be pingable in specific channels

young dagger
#

So if tier Unranked it should not show Unranked twice in the embed for the teams

young dagger
sick birch
#

You could probably make a lambda for that

#

pass that into map

#

Me personally I would create an abstraction layer for whatever datatype u is

#

And implement __str__ for it

#

So I can just do something like

team_1_ranks = map(str, team_1)
sick birch
#

It seems like user is a dict?

young dagger
#

So it should create a list for each user representing Discord mention, Summoner Name, Tier+Rank and Elo Rating

sick birch
#

Abstract it into it's own class:

class User:
  def __init__(self, ...) -> None:
    ...
  
  def __str__(self) -> str:
    return f"{} {} {}"
young dagger
#

Is it better to use regular expression or mapping when you have a fixed set of inputs that you want to map to specific outputs?

naive briar
#

I saw what you have deleted

young dagger
#
    # Find the league entry for the RANKED_SOLO_5x5 queue
    for entry in response.json():
        if entry['queueType'] == 'RANKED_SOLO_5x5':
            tier = entry['tier']
            rank = entry['rank']
            break
    else:
        # If no RANKED_SOLO_5x5 entry was found, return "Unranked"
        return "Unranked"

    # Capitalize the first letter of the tier
    tier = tier.capitalize()
    # Get the rank from the rank mapping
    rank = rank_mapping.get(rank)

    return f"{tier} {rank}"```
young dagger
#

I think this is more organized

#

@sick birch So you wouldn't use this method:

    team_1_ranks = [f"{u['tier_and_rank']} ({u['elo_rating']})" for u in team_1]

    team_2_ranks = [f"{u['tier_and_rank']} ({u['elo_rating']})" for u in team_2]

    team_1_names = [f"{u['summoner_name']}" for u in team_1]

    team_2_names = [f"{u['summoner_name']}" for u in team_2]```
sick birch
#

probably not

#

If u is a User class, you can just use u.summoner_name and u.tier_and_rank

young dagger
young dagger
sick birch
#

if team_1 is list[User] yeah

young dagger
# sick birch if `team_1` is `list[User]` yeah

Here is the list for both teams:

    # Shuffle the list of users
    random.shuffle(users)

    # Divide the users into two equal-sized teams
    num_users = len(users)
    team_size = num_users // 2
    team_1 = users[:team_size]
    team_2 = users[team_size:]```
sick birch
#

Ah, you're randomly assigning players to teams it seems

young dagger
sick birch
#

Did you actually convert the dict into a class?

young dagger
sick birch
#

Yea, they need to be converted to the class

#

You just pass in the appropriate values from the dictionary into the class constructor

ionic garden
#

i've heard somewhere it's possible to have like a general command and then some other things that narrow it down
for example

a.leaderboard, which shows all the possible leaderboards
a.leaderboard coins, which shows the coin lb
a.leaderboard trophies, which shows the trophy lb
etc. etc.
```is this actually a thing?
torn sail
#

is it possible to mention a builtin slash command?

torn sail
#

!d discord.ext.commands.group

unkempt canyonBOT
#

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

This is similar to the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.

Changed in version 1.1: The `cls` parameter can now be passed.
ionic garden
#

does it work w/ slash commands?

torn sail
#

but note that in app commands only the child command can be invoked. So /group cant be called, only /group subcommand

ionic garden
#

is there a hybrid command group?

young dagger
torn sail
unkempt canyonBOT
#

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

This is similar to the [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group") decorator except it creates a hybrid group instead.
ionic garden
#

nice

young dagger
sick birch
#

Are you trying to add a user to voice channel?

young dagger
sick birch
#

Is users the list of all users in the voice channel?

sick birch
#

So shouldn't you be appending new User objects to a new list?

#

You'd get duplicates in users then

young dagger
shrewd fjord
#

:0

sick birch
#

Is this all for just displaying in an embed btw?

shrewd fjord
#

Robin, hewo

sick birch
#

Howdy! softHaw

shrewd fjord
#

Hru:))

sick birch
shrewd fjord
sick birch
#

All you need is 2 lists comprising of User objects

#

team1 and team2

sick birch
young dagger
shrewd fjord
#

maybe do for loop?

sick birch
shrewd fjord
#

!e

msg="bla bla"
m=""
for e in msg:
  m+=e
print(m)
unkempt canyonBOT
#

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

bla bla
young dagger
shrewd fjord
#

For embed, altho too old πŸ—Ώ

sick birch
#

I recommended that it be

#

I'm assuming that it's list[User]

shrewd fjord
#

Ye

shrewd fjord
#

Maybe dict?

sick birch
#

In which case:

user: list[User] = [...]

team_1_ranks = list(map(str, team_1))
team_1_names = [u.summoner_name for u in team_1]

# same for team 2
#

It's important that the __str__ of User is how you want it to display

junior burrow
#

i am using discord.py to run a discord bot i am hosting; when i run the but code in pycharm (which is what ive been using) it works; but when i run it on my PC, it doesnt run... when i run a non discord.py program it works fine, any help? when i use pip install discord (i dont think thats it exactly but im close), it says it is already installed. any ideas?

young dagger
junior burrow
sick birch
junior burrow
#

just double click the py file

sick birch
#

You won't need the other 4 lists that way

shrewd fjord
#

Pycharm is a IDE, u can use it on pc anyway

shrewd fjord
junior burrow
#

yes but it uses 2gb ram, and id much prefer to run it in the basic python window when im not working on it

shrewd fjord
#

If u double click .py file it's going to open, but in pycharm it runs the file on console

#

U can also run it on console...

junior burrow
#

it closes right away when i open it

shrewd fjord
#

open cmd promt

#

And enter the exact file directory on cmd and hit enter

junior burrow
#

good point i shouldve tried cmd

shrewd fjord
#

It should come online right way

young dagger
# sick birch You may as well just do ```py embed.add_field(..., value="\n".join(f"> {u.summon...

He is the full embed:

    # Add the two teams and their ELO ratings to the embed
    embed.add_field(name="Custom Team 1", value=f"".join(f"\n> {u['member'].mention}" for u in team_1),
                    inline=True)
    embed.add_field(name="Summoner Name", value='\n'.join(f"> {name}" for name in team_1_names), inline=True)
    embed.add_field(name="Rank", value='\n'.join(f"> {rank}" for rank in team_1_ranks), inline=True)

    embed.add_field(name="Custom Team 2", value=f"".join(f"\n> {u['member'].mention}" for u in team_2),
                    inline=True)
    embed.add_field(name="Summoner Name", value='\n'.join(f"> {name}" for name in team_2_names), inline=True)
    embed.add_field(name="Rank", value='\n'.join(f"> {rank}" for rank in team_2_ranks), inline=True)```
junior burrow
#

one second

sick birch
young dagger
# shrewd fjord What's the problem

Robin recommended me not to use:

    team_1_ranks = [f"{u['tier_and_rank']} ({u['elo_rating']})" for u in team_1]

    team_2_ranks = [f"{u['tier_and_rank']} ({u['elo_rating']})" for u in team_2]

    team_1_names = [f"{u['summoner_name']}" for u in team_1]

    team_2_names = [f"{u['summoner_name']}" for u in team_2]```
junior burrow
# junior burrow one second

Traceback (most recent call last):
File "D:\python\discord\fp.py", line 2, in <module>
import discord as dis
ModuleNotFoundError: No module named 'discord'

#

i have imported discord though

#

kek

sick birch
#

@junior burrow it's worth noting that pycharm uses a seperate venv

#

So you can't just pip install package from your command prompt and have pycharm recognize it

junior burrow
#

yes yes

#

i had to do it seperately

#

for both

#

but it wont work on regular python

#

ive tried cmd

young dagger
sick birch
#

Yeah it's working
You just extract the information you want from it
It looks like you have {"member": member} which I'm not sure is desired

junior burrow
#

if not thats fine kek

young dagger
#

@sick birch Should I change it to:

    embed.add_field(name=":crossed_swords: Custom Team 1", value=f"".join(f"\n> {u['user'].mention}" for u in team_1),
                    inline=True)```
#

Nope,
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'user'

junior burrow
#

someone ping me when you have a solution, tyty

#

jsyk for the future i do not mind pings

young dagger
sick birch
#

If dict, what's it's structure?

lusty smelt
#

Wonder if that is json data given its League data

slate swan
#

Hi, what is the most reliable way to tree sync()? Currently, I'm syncing application commands on on_ready.

sick birch
#

setup_hook

young dagger
lusty smelt
sick birch
sick birch
#

So nothing wrong with that

slate swan
sick birch
#

But if you'd like you can have a dedicated sync command

lusty smelt
#

I get that it runs once; it's due in part from constantly restarting your bot during development.

#

That's the caution.

sick birch
sick birch
#

In production, however, your bot script shouldn't be restarted so often that the syncing is being problematic

lusty smelt
#

Mhmm that is true. I guess I assumed they were globally syncing.

sick birch
#

No yeah, it's fair to assume you'd globally sync in prod and sync to a specific guild in dev

sick birch
#

With the type of hosting options people are going for these days it does happen :P

lusty smelt
#

Oh yea.. gotta love those "bot hosting sites for free"

sick birch
#

(Looking at you replit)

lusty smelt
#

I wasn't going to name drop.

sick birch
#

Well replit should get it's pride kicked out from under it at times

lusty smelt
#

True, it's the user base issues

sick birch
#

@young dagger sorry I couldn't help you further - I have to be off to bed now
If you've got any questions do drop them here and either someone else can help you out or I will tomorrow
Thanks for your patience with me πŸ™‚

fair shuttle
#

is there anything wrong w that im trying to make the banner command?

shrewd fjord
#

And thus returning None

#

!e
print(None.url)

unkempt canyonBOT
#

@shrewd fjord :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: 'NoneType' object has no attribute 'url'
junior burrow
#

speaking of banners, how do i make GIF banners work without using two links, one for gifs, and one for PNGs

fair shuttle
shrewd fjord
#

Or just u can do...member.banner.url_as or something

#

Need to check docs

junior burrow
#

if i do .gif, it only works with people with gif banner

#

if i dont do .gif, it only shows a still image

#

if i use both, it isnt as clean looking

shrewd fjord
#

member.banner.url.replace('gif','png') altho not recommended

shrewd fjord
#

U no need to worry about changing banner url to gif or png

junior burrow
#

any solutions on my previous issue

#

?

shrewd fjord
#

What's the prob?

shrewd fjord
#

...

shrewd fjord
#

Doing something on cmd pretty hard πŸ’€

smoky sinew
shrewd fjord
#

U did this?

#

πŸ’€πŸ’€

junior burrow
#

'pip' is not recognized as an internal or external command,
operable program or batch file.

shrewd fjord
#

wait forgor the cmd idk if it's correct πŸ—Ώ

smoky sinew
junior burrow
#

Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

shrewd fjord
smoky sinew
#

first of all, it's python on windows not python3 @junior burrow

smoky sinew
#

pip comes with python, you don't install it

shrewd fjord
#

Unless some bad installation

#

I had to install manually πŸ˜”

junior burrow
smoky sinew
#

@junior burrow, does running python work?

shrewd fjord
#

In cmd prompt

junior burrow
smoky sinew
#

what problem are you having

#

are you using an IDE??

shrewd fjord
junior burrow
junior burrow
smoky sinew
#

@junior burrow your IDE uses a different python installation, probably a virtual environment

shrewd fjord
smoky sinew
#

you will need to install the discord.py package separately

junior burrow
shrewd fjord
#

Alr imma head out PU_PeepoLeaveExit

junior burrow
#

cya!!

shrewd fjord
#

;-;

young dagger
# sick birch <@386307484740222987> sorry I couldn't help you further - I have to be off to be...

Thanks. I fixed it:

            users.append(
                {"member": member, "summoner_name": summoner_name, "tier_and_rank": tier_and_rank, "elo_rating": elo})

    embed.add_field(name=":crossed_swords: Custom Team 1", value=f"".join(f"\n> {u['member'].mention}" for u in team_1),
                    inline=True)
    embed.add_field(name="Summoner Name", value='\n'.join(f"> {u['summoner_name']}" for u in team_1), inline=True)
    embed.add_field(name="Rank", value='\n'.join(f"> {u['tier_and_rank']} ({u['elo_rating']})" for u in team_1), inline=True)

    embed.add_field(name=":crossed_swords: Custom Team 2", value=f"".join(f"\n> {u['member'].mention}" for u in team_2),
                    inline=True)
    embed.add_field(name="Summoner Name", value='\n'.join(f"> {u['summoner_name']}" for u in team_2), inline=True)
    embed.add_field(name="Rank", value='\n'.join(f"> {u['tier_and_rank']} ({u['elo_rating']})" for u in team_2), inline=True)```
smoky sinew
#

ah wait i forgot pip doesnt work for you

junior burrow
smoky sinew
#

yeah

fair shuttle
#

either im too high or im js fucking too high but whats da problem w that

shrewd fjord
fair shuttle
#

ah

#

lol sorry

shrewd fjord
#

;-;...

fair shuttle
#

not a great idea to code when im stoned ig

shrewd fjord
#

Do this.....

#
if member.banner is None:
  return await ctx.send("Seems like you don't have banner lol")```
smoky sinew
junior burrow
#

i love rivulet

shrewd apex
#

u can do it without ide as well

shrewd fjord
#

I said him to do on cmd prompt but he having prob πŸ—Ώ

naive briar
shrewd fjord
rare echo
#

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

rare echo
#

@static sorrel

static sorrel
#

yeah, here

severe skiff
#

can someone help me i want that my bot saves the image i send then he sends it back

naive briar
#

!d discord.Message.attachments

unkempt canyonBOT
naive briar
#

Convert it to file then send it back

shrewd fjord
#

Please send the error

naive briar
#

There are so many things wrong with that

slate swan
#

Enable intents

naive briar
#

They already did

#

And that error isn't even from the code they just sent

slate swan
#

blocking io 🚢

severe skiff
slate swan
# severe skiff bro but HOW CAN I DO THIS

you use . attachments attribute of the message object which gives you a list of attachments in the message, then use attachment.to_file() to convert it into a file and send it

#

!d discord.Attachment.to_file

unkempt canyonBOT
#

await to_file(*, filename=..., description=..., use_cached=False, spoiler=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Converts the attachment into a [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") suitable for sending via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send").

New in version 1.3.
hollow lark
#

I need help

#

I CAN'T FIX THISS

#

d! TypeError Client.init() missing 1 required keyword-only arguments: 'intents'

naive briar
#

Read the error

hollow lark
#

!d TypeError Client.init() missing 1 required keyword-only arguments: 'intents'

unkempt canyonBOT
#

exception TypeError```
Raised when an operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch.

This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. If an object is meant to support a given operation but has not yet provided an implementation, [`NotImplementedError`](https://docs.python.org/3/library/exceptions.html#NotImplementedError "NotImplementedError") is the proper exception to raise.

Passing arguments of the wrong type (e.g. passing a [`list`](https://docs.python.org/3/library/stdtypes.html#list "list") when an [`int`](https://docs.python.org/3/library/functions.html#int "int") is expected) should result in a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError"), but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "ValueError").
hollow lark
#

I did read it

naive briar
#

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

hollow lark
#

I can't fix it

naive briar
hollow lark
#

What's mandatory?

slate swan
#

mandatory means required

severe skiff
#

should i use this?

slate swan
#

yes

severe skiff
#

aight

#

ty

#

message is underlined lol

#

why is attachement and message underlined?

#

bruh

#

nvm fixed

#

wt

#

@client.command()
async def setimg(ctx):
    attachment = nextcord.Message.attachments
    if message.Attachment: 
        await attachment.to_file(filename=f"{attachment.name}",use_cached=False, spoiler=False)
        await ctx.send(attachment)
    if not message.Attachment:
        await ctx.send("please send a attachement")

#

help

#

Command raised an exception: AttributeError: 'member_descriptor' object has no attribute 'to_file

#

@slate swan sorry for ping but can u help

meager chasm
#

You need an instance of the class, which you can get from ctx.message

severe skiff
#

tysm

meager chasm
#

And there is no .Attachment attribute for Message

#

You can see all the attributes in docs

severe skiff
severe skiff
#

cuz i cant find the Attributes in the website...

meager chasm
#

!d nextcord.Message

unkempt canyonBOT
#

class nextcord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

x != y Checks if two messages are not equal.

hash(x) Returns the message’s hash.
meager chasm
#

Go to that link

severe skiff
#

.-.

meager chasm
#

Ok so you can use that

severe skiff
#

attachment = nextcord.Message.attachments

#

like this?

vocal snow
#

No...

vocal snow
severe skiff
#

thx

vocal snow
#

Id recommend learning classes in python to understand this

severe skiff
#

Command raised an exception: AttributeError: 'list' object has no attribute 'to_file'

#

@client.command()
async def setimg(ctx):
    attachment = ctx.message.attachments
    if message.Attachment: 
        await attachment.to_file(filename=f"{attachment.name}",use_cached=False, spoiler=False)
        await ctx.send(attachment)
    if not message.Attachment:
        await ctx.send("please send a attachement")
#

WHERE DID I TYPE LIST

naive briar
#

message.attachments returns a list

#

Reading the docs would have told you that

severe skiff
#

and how can i fix it?

sudden nacelle
#

How can I get the bot to ping reply to the user instead of it just sending a blank message in this kick error code:

@kick.error
async def kick_error(interaction: discord.Interaction, error):
    error = getattr(error, "original", error)
    await interaction.response.send_message("You do not have permission to kick people!", delete_after = 5)```
slate swan
#

woof

naive briar
#

And why are you using getattr function

sudden nacelle
slate swan
#

right. it's safer to use getattr because not all error instances have original attr

#

but your question is still not much clear

sudden nacelle
#

I want it so the missing permission one has the discord ping like the top one

slate swan
#

oh

#

then just ping the user?

#

@static bane you don't have permission to kick people ( sorry for ping )

sudden nacelle
naive briar
#

Why do you want to mention the user anyway

#

It clearly shows who uses the command

sudden nacelle
#

Figured it would stand out more to the person trying to execute the command

naive briar
#

There's no other option than to mention them in the response

sudden nacelle
#

I see, thank you for helping guys :]

young dagger
#

@sick birch Do you know why did it work with {u['summoner_name']}" for u in team_1 and not {u.summoner_name}" for u in team_1

naive briar
#

What is the context here yert

shut axle
#
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  client.load_extension(f'cogs.{filename[:-3]}')

Do you know what is this problem?

naive briar
#

You need to await the coroutine the load_extension function returns

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

Should I await the client.load_extension?

golden portal
#

yes, its coroutine

shut axle
#

It is not allowed

naive briar
#

Do it in setup_hook

#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
distant python
#

all answers on google are from when discord.py was discontinued

golden portal
distant python
#

ok ty

golden portal
#

welcome

young dagger
#

What is wrong with this code? I'm seeing Unexpected argument and Parameter '__value' unfilled

            # Send an embedded message to the specified channel
            channel = discord.utils.get(member.guild.text_channels, id=745832392404762695)
            avatar_url = client.user.avatar.url
            embed = discord.Embed(description=f'Size: **{len(new_members_list)} accounts**', timestamp=datetime.datetime.now(), color=discord.Color.red())
            embed.set_author(name="Here is the list", icon_url=avatar_url)
            embed.set_footer(text="Lis for today.")
            await channel.send(embed=embed)```
#

I don't understand what could be wrong with await channel.send(embed=embed)

shut axle
#

@naive briar I tried many things but I couldn't success can you give me an example pls?

young dagger
slate swan
#

Good day!
I need help...

I want a Discord command that tells me if my server is online or offline...
Can someone help me?

The problem is... The message is not sent because the cmd ping command is blocking it...

(I try like in the photo)

Kind regards

distant python
#

has something changed?

import discord

from discord.ext import commands


class DiscordBot(commands.Bot):
    def __init__(self) -> None:
        intents = discord.Intents.default()
        intents.members = True
        intents.message_content = True

        super().__init__(
            command_prefix='.',
            case_insensitive=True,
            intents=intents
        )

    async def on_ready(self) -> None:
        print(f'Signed in as {self.user.display_name} on Discord.')

    @commands.command()
    async def ping(self, ctx: discord.ext.commands.Context) -> None:
        await ctx.send('plup')


bot = DiscordBot()
bot.run('TOKEN')

discord.ext.commands.errors.CommandNotFound: Command "ping" is not found

slate swan
#

commands defined like that don't get automatically added to the bot

#

that works only in cogs

slate swan
sick birch
young dagger
# sick birch Exactly why

Alright. I got confused cause you told me to use {u.summoner_name}" for u in team_1. Should I redo the code to use it or just leave it as it is?

sick birch
#

You don't need to

young dagger
#

@sick birch What is the different by using {u.summoner_name}" for u in team_1 and {u['summoner_name']}" for u in team_1 anyway?

sick birch
#

Me personally I would go for the class simply because of that extra abstraction layer

#

I can add custom errors, override str, implement custom operators

#

Just good practices you know

shut axle
slate swan
#

hm

slate swan
# shut axle

pretty sure that bot is just matching their own emoji with the user_flags. don't think you can actually get that logo from user_flags just what the user has

#

!d discord.Member.public_flags

unkempt canyonBOT
#

property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.public_flags "discord.User.public_flags")
fair shuttle
#

whats wrong w this iont understand

sick birch
fair shuttle
#

the string is at the end?

fading marlin
#

You have to use triple quotes, or use \n to express a new line

vale wing
# fair shuttle the string is at the end?

3 ways of doing multiline string

"""Hi, I have
Three hundred dollars"""

"Hi, I have\n\
Three hundred dollars"

("Hi, I have\n"
"Three hundred dollars")  # braces are needed depending on case
jaunty hare
#

hi! somebody knows how to get the user id with discord.py?

slate swan
#

anyone know why this isnt working?

channel_cre_values = {}

@bot.event
async def on_guild_channel_create(channel):
    global channel_cre_values
    server_id = channel.guild.id
    if server_id not in channel_cre_values:
        channel_cre_values[server_id] = 2
    creation_count = 0
    # Get the audit logs
    audit_logs = await channel.guild.audit_logs(limit=1, action=nextcord.AuditLogAction.channel_create).flatten()
    # Get the user who created the channel
    user = audit_logs[0].user
    member = channel.guild.get_member(user.id)
    # Check if the user has created more than the maximum allowed number of channels
    if creation_count >= channel_cre_values[server_id]:
        await member.ban()
        print(f"Banned user {user.name} for nuking.")
    else:
        creation_count += 1```
ebon island
#

What is it doing? When you ask questions describe your problem or any related exceptions

slate swan
#

im not getting an erorr

#

or anything

ebon island
#

Run in debugger and see what the code is doing when that executes

slate swan
#

im not getting a error

static holly
#

hi! what is the best hosting website for my bot with GitHub repo ?

#

i leave in france

thin oar
#

anyone else having errors with the discord py servers?

#

had it since yesterday

white citrus
#
future: <Task finished name='discord-ui-view-timeout-a7a51714d780d1b0c2a275f266706616' coro=<HelpView_Slash.on_timeout() done, defined at c:\Discord\Maja Projekt\MajaSystem_Test\modules\helpV2\cog.py:63> exception=AttributeError("'coroutine' object has no attribute 'edit'")>
Traceback (most recent call last):
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\helpV2\cog.py", line 66, in on_timeout
    await self.message.edit(view=self)
AttributeError: 'coroutine' object has no attribute 'edit'
vocal snow
vocal snow
#

You're awaiting the .edit, not the self.message

sick birch
#

Why would self.message be a Coro pithink

vocal snow
#

Because they've defined it as such probably

#

Likely not intentionally

white citrus
bright wedge
vocal snow
#

You need the id to use get_member/get_user...

jaunty hare
#

with what symbol i write code?

primal token
unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

primal token
#

you mean format?

jaunty hare
#

yeh thanks

autumn totem
white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 489, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 275, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 888, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup_v2\cog.py", line 781, in setup_bot
    f"> Administrator Role {c.MajaCrossMark if admin_role is None else c.MajaCheckMark}\n" f"> {get_admin_role.mention} \n\n"
UnboundLocalError: local variable 'get_admin_role' referenced before assignment```
#

It is definied Shrug

slate swan
#

UnboundLocalError: local variable 'get_admin_role' referenced before assignment

white citrus
#

I can read errors Thonk

slate swan
#

then fix it

white citrus
#
        async with aiosqlite.connect("maja.db") as db:
            async with db.cursor() as cursor:
                
                await cursor.execute('SELECT admin_role FROM setup WHERE guild_id = ?', (inter.guild.id,))
                admin_fetch = await cursor.fetchone()
                if admin_fetch is None:
                    admin_role = None
                else:
                    get_admin_role = inter.guild.get_role(admin_fetch[0])
                    admin_role = admin_fetch[0]
                
                
                await cursor.execute('SELECT moderator_role FROM setup WHERE guild_id = ?', (inter.guild.id,))
                mod_fetch = await cursor.fetchone()
                if mod_fetch is None:
                    mod_role = None
                else:
                    get_mod_role = inter.guild.get_role(mod_fetch[0])
                    mod_role = mod_fetch[0]


                await cursor.execute('SELECT supporter_role FROM setup WHERE guild_id = ?', (inter.guild.id,))
                sup_fetch = await cursor.fetchone()
                if sup_fetch is None:
                    sup_role = None
                else:
                    get_sup_role = inter.guild.get_role(sup_fetch[0])
                    sup_role = sup_fetch[0]
                
                
                await cursor.execute('SELECT log_channel FROM setup WHERE guild_id = ?', (inter.guild.id,))
                log_fetch = await cursor.fetchone()
                if log_fetch is None:
                    log_channel = None
                else:
                    get_log_channel = inter.guild.get_channel(log_fetch[0])
                    log_channel = log_fetch[0]
                    
                    
                await cursor.execute('SELECT global_channel FROM setup WHERE guild_id = ?', (inter.guild.id,))
                global_fetch = await cursor.fetchone()
                if global_fetch is None:
                    global_channel = None
                else:
                    get_global_channel = inter.guild.get_channel(global_fetch[0])
                    global_channel = global_fetch[0]
                    
                    
                await cursor.execute('SELECT language FROM setup WHERE guild_id = ?', (inter.guild.id,))
                language_fetch = await cursor.fetchone()
                if language_fetch is None:
                    language = None
                else:
                    language = language_fetch[0]
                print(admin_role)
                status_embed = nextcord.Embed(title="SETUP β€’ Status", description=
                            f"> Administrator Role {c.MajaCrossMark if admin_role is None else c.MajaCheckMark}\n" f"> {get_admin_role.mention} \n\n"
                            f"> Moderator Role {c.MajaCrossMark if mod_role is  None else c.MajaCheckMark}\n" f"> {get_mod_role.mention}\n\n"
                            f"> Supporter Role {c.MajaCrossMark if sup_role is None else c.MajaCheckMark}\n" f"> {get_sup_role.mention}\n\n"
                            f"> Log Channel {c.MajaCrossMark if log_channel is None else c.MajaCheckMark}\n" f"> {get_log_channel.mention}\n\n"
                            f"> Global Channel {c.MajaCrossMark if global_channel is None else c.MajaCheckMark}\n" f"> {get_global_channel.mention}\n\n"
                            f"> Language {language if language else c.MajaCrossMark}\n\n", colour=c.gold)```
autumn totem
white citrus
white citrus
primal token
unkempt canyonBOT
#

@primal token :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 4, in <module>
003 |   File "<string>", line 2, in foo
004 | UnboundLocalError: cannot access local variable 'bar' where it is not associated with a value
primal token
#

You're basically trying to access get_admin_role which might not be available depending if admin_fetch isnt None

golden edge
slate swan
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. 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.

fair shuttle
#

im trying to do slash commands rn and i got this error i think i installed everything

#

first time im doing that so im sorry if this is stupid lol

#

i installed this idk if it was needeed

slate swan
#

Anyone know how to interact with a ticket tool panel using discord api

smoky sinew
#

and use a real IDE or code editor

fair shuttle
#

why whats wrong w replit lol

primal token
#

What's a fake editor

upbeat gust
upbeat gust
upbeat gust
primal token
smoky sinew
primal token
wary crystal
#

TFW when GitHub codespaces (hosted VSCode) isn't a real editor

slate swan
#

code:

        print("Current working directory:", os.getcwd())
        async with aiofiles.open("team_log.txt", "a") as file:
            print("File path:", file.name)
            file.write(f"{user.name} ({user.id}) joined team {team.name}\n")
            print("File written to successfully")
        await interaction.send(f'Sent offer to {user.mention}`{user}`', ephemeral=True)```

What terminal is saying:

```Current working directory: C:\Users\mzsma\Desktop\open3
File path: team_log.txt
File written to successfully
PS C:\Users\mzsma\Desktop\open3>```

But it isnt writing anything in the team_log.txt file, any help?
hushed galleon
naive briar
#

Who would have thought, huh

spice jewel
#
await ctx.send(":001callisto: **WARNING: This will remove the user entirely from the system, would you like to proceed?** :001callisto:")
msg1 = await spooky.wait_for("message", check=lambda x: x.author == ctx.author)
    if msg1.content == "y":
        await ctx.send("What is the reason for removing?")
        msg2 = await spooky.wait_for("message", check=lambda x: x.author == ctx.author)
        await member.remove_roles(defined_roles)
        await member.edit(nick=None)
        dynamic_timestamp = discord.utils.format_dt(datetime.now(), style="R")
        remove=discord.Embed(
            title=f"User Removed - {member.tag} ✦", 
            timestamp=datetime.datetime.utcnow(),
            color=discord.Color(0xac0101)
                )
        remove.add_field(
            name="User ID:",
            value=f"``{member.id}``"
                )
        remove.add_field(
            name="Reason:",
            value=msg2.content,
            inline=False
                )
        remove.set_footer(text=f'{member.id}')
        await ctx.send(embed=remove)```
#

recognises content of the first message (y) and responds correctly but for msg2 it doesn't respond with anything, does anyone know why?

elfin cloud
#

hello, im wondering how i make it so even when if someone doesnt have a profile picture, it still shows the default profile picture that they have on a command

#

because right now i have it so its ctx.author.avatar.url but it gives me the error: e.set_author(name=f'{ctx.author.name}', icon_url=ctx.author.avatar.url) AttributeError: 'NoneType' object has no attribute 'url'

fading marlin
#

!d discord.Member.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
elfin cloud
#

ah ok thank you

fading marlin
#

You're welcome

fossil talon
#

hey so im sending a request to discord, and one of the values for the dict is over 2k characters, i cannot shorten this, when i send this request to discord, i get 50035 error, can someone pls help?

sick birch
slate swan
#

I'm trying to reply in a message using a message id but idk how to do it that uses a channel to reply to it. i tried this but won't work

    ch = interaction.guild.get_channel(CHANNEL_ID)
    message = await ch.fetch_message(ids)
    await message.reply(embed=emb)
terse coyote
#

is it possible to send an embed image as a spoiler?

sick birch
pulsar bridge
#

You guys know how some bots can send images, but the images slightly change depending on different variables inputted?
Like, lets say the image is of a.. cup of coffee. But the color of the coffee changes depending on their role color.
Or A picture of a landscape, but the sun is replaced by the profile picture of the triggering user.
I have... absolutely no idea on where I'm supposed to start... or what to search up to find out where to start... ideas?

sick birch
pulsar bridge
#

Sounds great!
Where can I start? Kek

sick birch
#

I would not recommend tackling unless you 110% sure you know what you're doing and you're fairly advanced

pulsar bridge
#

Hmm...
That sounds.. painful.
But I've got time to learn

sick birch
pulsar bridge
#

And this.. Pillow will be able to do both the examples I provided above?

#

It will be able to!

#

Thanks, Robin!
Always helpful DC_happy

sick birch
#

thank

spiral crypt
#

i have a logic question

progress += (datetime.datetime.utcnow() - progress).total_seconds()
user_time_in_server["progress"] = progress

Assuming this does what I want, starting with progress of 0, and it checks every 5 minutes will it update the "progress" key to 300 properly?

spice jewel
jade laurel
#

Do u have a error handler?

spice jewel
jade laurel
#

try removing msg2 line

grizzled crown
#

anyway to get code of a bot on a discords server?

#

like to copy it and learn

shrewd fjord
brisk oar
#

where do i host my discord bot

naive briar
#

A VPS

vale wing
vale wing
spiral crypt
#

Yeah i think i did something along the lines of round((datatime.datetime.now() - member.joined_at).total_seconds, 0)

brisk oar
grizzled crown
#

I was hoping for like a javascript thing where nothing is really closed source but guessing discords bots isn't anyway similar in being able to copy code?

slate swan
#

can you use rich presence for the change_presence for a bot? or is it not possible?

cunning pasture
cunning pasture
naive briar
#

Just simple playing, watching, blah blah blah.

naive briar
#

!d discord.utils.utcnow

unkempt canyonBOT
#

discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.

This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.
cunning pasture
cunning pasture
# naive briar Possibly

This is what I have

f"{datetime.datetime.utcnow() - member.joined_at.replace(tzinfo=None)}"

Not sure if that's needed or not though tongue

slate swan
#

using a unix timestamp is far better

grizzled crown
#

or any sort of discords bot copier would be nice if there is one

#

not sure if its possible as maybe its mainly server side and idk if that code is viewable

#

I think mainly client side code is viewable so not sure how most discords bot work, new to it

slate swan
#

you can't view any bot's source code from discord
the only way to access to it is the actual programmer sharing it somewhere

grizzled crown
#

why is that?

slate swan
#

um,that's what backend is πŸ€·β€β™‚οΈ

#

a discord bot is not a web element that can be accessed through something like inspect tools

#

it's just like any other user on discord

winged linden
#

How can I check if a string is an emoji within a slash command?

pulsar bridge
#

Trying to download a user's avatar as a file... but it ain't working.

    id = interaction.user.id
    bg = Image.open('directory\\1\\background.png')
    bgc = bg.copy()
    pfp_url = interaction.user.avatar.url
    for url, save_basename in [
        (pfp_url, str(id))
    ]:
        response = requests.get(url)
        if response.status_code != 200:
            raise URLError
        extension = imghdr.what(file=None, h=response.content)
    async with aif.open(f'directory\\1\\{save_basename}.{extension}', 'wb') as file:
         file.write(response.content)

is what I have.
It saves the image with the correct name, but the image is corrupt.
As I'm the triggering user, the url (pfp_url) is https://cdn.discordapp.com/avatars/776940844728057928/f2c610c2befa7b4818186a07232977fc.png
And it saves correctly when I manually download it.
But when the code does it, It corrupt. (Image attached)

slate swan
#

!d discord.Asset.save

unkempt canyonBOT
#

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

Saves this asset into a file-like object.
slate swan
#

just use await user.avatar.save()

#

with the file path ofc

slate swan
unkempt canyonBOT
#

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

The method to override to do conversion logic.

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

use this to try converting the string to an emoji

winged linden
shrewd fjord
#

:0

shrewd fjord
spice jewel
pulsar bridge
shrewd fjord
#

Vanessa πŸ’€

#

Vanessa's trick working, good job as spark said

jade laurel
shrewd apex
naive briar
#

Sus emoji name

tidal plover
#

Can someone give me tldr on when did discord enforce slash commands and why did people have to rewrite their bot codes from scratch? I mean commands without slash still work with prefixes on so many bots