#discord-bots
1 messages Β· Page 184 of 1
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.
Or using choices
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}")
I tried doing setting:bool
member_mention.mention
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
ok, thanks!
ok and how do i return a different message depending on whether i am mentioning someone or not?
Do you want it to be random or under a certain circumstance they get pinged
I want to display a simple answer without ping if I don't mention anyone, and display a different answer if I mention someone. I think that with if and else it should work but I have a doubt about the code
if mention== true > answer 1
else: answer 2
is correct?
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?
pass? what is this?
Nothing
replace pass with code
!d pass
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)
okay!
you put pass in spots you don't need code to run
okay, thanks π
I use it if I don't want code in that spot yet so it doesn't error lol
can you help with this bool thing
@commands.command(pass_context=True)
async def hug(self, ctx, *, member_mention:discord.Member=None):
user= ctx.author.display_name
if member_mention == None:
await ctx.send (f"{user} say hello")
else:
await ctx.send (f"{user} say hello to {member_mention.mention}")
somethin like that
anyone know is there is something i can use like active_developer to flag if the user has that badge?
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"))
less go my bot got verified 
Read the error
!intents
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.
why do u have both client and commands.Bot u need only 1
Tell the error then
It won't be there if there's nothing wrong
smart
yh but thats true
I aint long into coding bots
since yesterday
uhhh sometimes I asked chatgpt for help maybe it dont smth wrong
yeah, you only need one (preferably commands.Bot)
Alright thanks
π we need a warning note for chatgpt with discord bots
Yeah haha
we already had an announcement for chatgpt in general
Thanks It worked
β€οΈ
π
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
!or
There's a built-in way to do it apparently https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#help-commands
I haven't used it before though
same, i've always did a custom one before
!customhelp
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
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
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
you're missing a ,
after "application/json"
okay
why are you using the clash of clans api though π€£
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
why are u laughing lmao
example_fstring = f'Bearer {key}'
I believe they are aware of how to use f strings as they have used it in their command
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
Anyone knowledgeable on the subject have guidance on the above btw? Going to be roughing out implementation today so wanted to get the inside scoop on efficient implementation
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
I would just use queues
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?
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
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
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!
Idk I still do errors messages with % op idk why
how do you timeout a member
!d discord.Member.timeout
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").
how would that be coded?
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
tab the await down one or remove the return
I removed the return and the bot just send messages in a loop
try it the other way
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
Use listen() instead of event
no event is correct here
assuming they are doing this in a singular file
Event can't be "correct"
Do yk difference between event and listen()
Why are you guys attacking the poor lad
no because I don't use listeners outside of cogs
or I just subclass my bot
!d discord.ext.commands.Bot.listen
@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...
okay...
Cog.listener() is a different thing
listeners are better overall, you avoid many abstraction issues
They're both listeners lol
Yes
it isn't
I never said it's not a listener
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello
002 | World!
Or triple quotes
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.
lovely dir
@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
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?
Easy, it's nextcord
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))
first block is the main file
@vocal plover
π
second block is the file solebox, inside cogs folder
if anyone has an idea im willing to take haha
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
Can't always deny the facts
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.
anyone idea>>
the command is indented too far in your cog class, it should be at the same level as __init__, not within that function
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
wym?
in my main.py?
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
@vocal plover
I don't help with music bots since they generally violate Discord's and YouTube's terms of service
π okay thanks
Still not working
Show new code
yeah thank you man
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.
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
on_command_error*
Not sure if nextcord has separate events for slash commands
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...
switched to on_application_command_error
but I still do not get any message
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x0000020515B0BF10>:
I get this idk why
Why tf they put it into checks π
@upper root error handler should raise unknown exceptions
if isinstance(err, SomeError):
...
else:
raise err```
So what do I change it to ? err, SomeError
π
how can i get the id of user launched slash command
And for example letβs say I want to stop using nextcord because Iβm getting too confused Xd. Could I do a simple file called handlingerrors.py and import it into my main.py and in this file. I add all my errors handling
Will that be possible ? And if so what should the form of the file handlingerrors look like ?. A simple @client.event
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"))
await bot.get_channel(channel_premium_id).send(embed=log_embed)
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'```
How do you run your bot and what other async packages do you utilize (db, web, etc)
I'm using systemd, and using asyncpg, and pillow (run_in_executor)
Do you use asyncpg client or you embed API
explain a bit more...
Do you just make requests with it or you have API server embedded into bot
I still don't get it, but the postgres server is hosted on the same server as the bot
Ok then you just make requests if you don't understand what I mean
Instead of systemd I recommend using docker, might solve the issue https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
how do make it so if the error is not missing permission it gets displayed in console normally
Add an else block and raise error
thanks
anyone else having problems with the discord servers?
aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
send here or to pv?
Here
how are you connecting to your database
credentials1 = {"user": "user", "password": "pass", "database": "main", "host": "localhost"}
bot.conn = await asyncpg.create_pool(**credentials1, max_inactive_connection_lifetime=10)
what is the disconnect message
nothing?
that doesn't make sense.
too long xD
!paste
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.
you say your bot is disconnecting yet you don't see anything about a disconnect in console?
Send only part that is related to your issue
I mean disconnected from discord itself, but the script loop just keeps running.
Show full traceback
yeah can you show us the message it provides in console when it's disconnected
It doesn't provide anything.
Do you have logging set up?
info level still provides logs on disconnect
Probably will be able to catch more stuff
i don't think it is being disconnected from discord. it sounds like a host issue
Hey @thin oar!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I'm hosting on galaxy gate, 8 GB 3 cores
you're missing message_content intent
oh nvm lmao i see it at the bottom
@simple plume you shouldn't be doing commands that way
It is after bot is actually run
also why are u running the client then defining bot wtf am i looking at
@simple plume take a look into this https://discordpy.readthedocs.io/en/stable/ext/commands/index.html
and ur using client and bot both lol
I'm new sry xD
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]
Mac or win?
I am running the code on ubuntu but my pc is win
Those are like completely different things
The error occurs on windows or on ubuntu?
looks like ubuntu
ty
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
So where
and I keep getting warning and this error
its a connection issue, most probably because of internet availability
I am using a cable
!d aiohttp.ClientConnectionError
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")
Or bad certificates
is your system setup to use it for intent?
never had to install certificates on linux
aiohttp.client_exceptions.ServerDisconnectedError: Server disconnected
One person had the same problem and reinstalling certificates helped
if that's the issue installing certifi should make it work
But yeah the error looks like connection issue
I already have that installed
Does ping to anything work
wdym?
ping google.com for example
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
I don't know if this is what you mean?
That's from same machine you run the bot from?
instead of using the discord.py module is it possible to do this in a json format
embed2.set_image(url="attachment://image.png")```
?
is it possible to upload an attachment with a json format
i may be in the wrong chat for this
You mean raw request to discord API?
ye
One sec
@slate swan check embed structure and specifically image field https://discord.com/developers/docs/resources/channel#embed-object-embed-structure
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
thanks
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
!pypi pillow
thanks
Command raised an exception: AttributeError: 'Message' object has no attribute 'wait_for'```
!d discord.Client.wait_for
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**...
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
seems like some xy problem
why would you need an extra arg in your command in the first place?
You can't use custom contexts in app commands from what I can tell
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
I feel like he just needs to set a botvariable
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?
you should consider using commands
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
oh ok
I will recode this with commands and then confirm, if it worked
my bot runs a game. users can start games. to make it easier, i represent game instances as classes, and use a decorator on those commands that are supposed to be run during a game. the decorator checks that a valid game instance exists and passes it into the command function
so still.. what's the extra arg for?
the game instance
why don't you use a database or whatever to store their progress?
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
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
yep. it worked alright before i started migrating to slash commands. parameter handling changed and now it doesnt accept that custom parameter
botvar?
!botvar
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!
maybe that's what you need to keep track of your "game instances"
i already keep track of my game instances using a self.games variable in the cog
alright, then still, what do you pass as extra arg in your command that's sΓ³ needed?
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
I would never handle that stuff in your decorator tbh
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
I'd just throw an error and let your error handler send that message
I see, but I still don't know what the command_arg is for
command_arg represents regular arguments that are supposed to be used client-side
How do you write a function to get a random tenor gif using a query?
that question has 2 parts
"how to get a random tenor gif by a given query?"
"how to give a query through a command?"
The first question
they didnt mention command...
alr, so I don't think you're allowed AND interaction AND ctx in a command, you'll have to pick one or the other
that's not really #discord-bots related, so maybe #βο½how-to-get-help
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.
you're still trying to "fix" your problem your way, while there are better solutions
you don't need the custom context passed to be able to use your custom decorator
is there a better way to wrap an app_command function?
yeah, there's most likely something documented about custom decorators in the docs
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
can you tell me once again why you need to pass arbitrary args and where exactly you use them?
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
have you tried the on_command event instead?
which can basically prevent or do whatever with certain commands before they're executed
can it pass arguments?
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
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.
that's why you use a database
maybe i could attach the game instance to the already existing interaction parameter
still have to retrieve from the database
& validate
duplicated code?
you're just editing the game progress in the db while making moves
I have to be able to reproduce it
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
mhm, not a problem
might be late to the show but why cant you just make a function for it instead of a decorator?
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
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
like 5 lines of code lol
- 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
!d discord.app_commands.CommandTree.interaction_check
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.
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
wait_for waits for an event, "none" is not an event
I see, how should I code it then? (bot asks "What is the reason for removing?" and whatever the user sends is stored in a variable and later used in an embed)
is "message" when they send any message?
correct
aka
"whenever an on_message event gets executed"
it's still not doing anything, here is the updated code:
but as the docs state, with wait_for, you don't have to type the on_\_
have you tried debugging? or are you guessing?
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)```
it says there are no bugs
not having any errors doesn't mean you don't have bugs
is this code correct though?
Run it and see β’οΈ
nothing happened after the bot asked the user the question
spoiler: no
HELP
Should be x.author == ctx.author
π₯
That's the message object
good, now the rest should be a piece of cake
yep ty!
remove.add_field(
name="Reason:",
value=f"msg",
inline=False
)```
yeah for the reason, when I made the value msg
it sent that whole strip of information
when I wanted it to be whatever the user said
what should I change it to?
now reading this why not use an autocomplete?
!d discord.Message
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
^
I'm still a bit confused with this π I'm not sure how to add it to my code
remove.add_field(
name="Reason:",
value=str(discord.message.content),
inline=True
)
await ctx.send(embed=remove)```
value = msg.content, you definitely have to look more into OOP programming before taking on such projects, you don't seem to have an understanding in the difference between a class and an object
yeah, as I explained I'm very new and trying to learn as I go/teach myself. Thank you for your help though <3
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
please, is it possible to add a variable in embed field?
!xy
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/
because i create a help command and i want enter server.text_channels number in str method
you what?
do you just want to add an extra field to an embed?
which shows how many text channels there are in your current guild?
yes with my number of text channels
!d discord.Embed.add_field
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.
just add a field to the embed and pass something in the name and value arg
yes, but i have a error
first time you're mentioning that
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
full error?
no just "(" was not closed
you don't want to write custom help commands like that
join the dpy official support server
#559455534965850142 message
then you'll be able to click on this link
i dont have acces at this link π
I told you how you could
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?
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?
The on_message event needs an argument to represent the sent message
Just add message or msg to the event's function arguments
Did you define it before trying to check its content
ok i got it working but now it is spamming the message like twice.... py lastmessage = '' @bot.event async def on_message(message): global lastmessage msg = message.content print(msg) if (repeat == True): if msg != lastmessage: await message.channel.send(content=f'{msg}') lastmessage = msg
yes sorry, the code I sent wasn't accurate compared to what was written, I just updated it above
^^ msg 1 works but msg 2 doesn't
What is the while loop there for
f"{msg}" is useless fyi, just use msg, it's already a string instance
nvm it was just repeating its own message
Can you leave description empty in embeds?
yes
still need help w this :)
so it seems discord slash commands dont support variadic arguments (similar to *args, or just a list-type argument). has anyone found any usable workarounds?
https://github.com/discord/discord-api-docs/discussions/3286
Aucomplete, like the one guy mentioned, is probably the best solution
Or just a regular string and split by , or some other delimiter
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
How many players?
2 to infinity, inclusive
no prob
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]```
Yeah do merge that
how to make a role in server pingable
Roles are pingable by default
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
This is how I keep things right now
So if tier Unranked it should not show Unranked twice in the embed for the teams
But it would end up with the same thing right? if u['tier'] != "Unranked" else f"Unranked ({u['elo_rating']})
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)
u = user
It seems like user is a dict?
So it should create a list for each user representing Discord mention, Summoner Name, Tier+Rank and Elo Rating
Abstract it into it's own class:
class User:
def __init__(self, ...) -> None:
...
def __str__(self) -> str:
return f"{} {} {}"
Something like this? https://paste.pythondiscord.com/onoyogikit
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?
mapping or list comps
I saw what you have deleted
# 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}"```
I will keep tier and rank as one field instead of two separate fields
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]```
probably not
If u is a User class, you can just use u.summoner_name and u.tier_and_rank
It creates a list using users = []
You mean like this?
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]```
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:]```
Ah, you're randomly assigning players to teams it seems
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'dict' object has no attribute 'tier_and_rank'
Did you actually convert the dict into a class?
I changed to this
I think I know what the issue is, team_1 and team_2 list are dictionaries and they don't have attributes such as tier_and_rank or elo_rating
Yea, they need to be converted to the class
You just pass in the appropriate values from the dictionary into the class constructor
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?
is it possible to mention a builtin slash command?
yep those are groups
!d discord.ext.commands.group
@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.
does it work w/ slash commands?
yes then it would be @app_commands.group()
but note that in app commands only the child command can be invoked. So /group cant be called, only /group subcommand
is there a hybrid command group?
So instead of:
users.append({"member": member, "summoner_name": summoner_name, "tier_and_rank": tier_and_rank, "elo_rating": elo})```
I should use:
```python
users.append(User(member=member, summoner_name=summoner_name, tier_and_rank=tier_and_rank, elo_rating=elo))```
!d discord.ext.commands.hybrid_group
@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.
And what is users?
nice
Each user in the voice channel
Are you trying to add a user to voice channel?
No its retrieving all users from a voice channel generating 2 teams
Is users the list of all users in the voice channel?
Yes
So shouldn't you be appending new User objects to a new list?
You'd get duplicates in users then
True. So should I create a list instead?
Example:
team_1_ranks = []
for u in team_1:
team_1_ranks.append(f"{tier_and_rank} ({elo_rating})")```
:0
Is this all for just displaying in an embed btw?
Robin, hewo
Yes
Howdy! 
Hru:))
I don't see the need to make like 4 different lists then
Fine 
I'm great, thanks for asking π
Can you explain this again please?
maybe do for loop?
Right. So you have the User class, with the same attributes your dict does
You just translate the dict to a class
We get the benifit of __str__ here which makes it a lot nicer to read
!e
msg="bla bla"
m=""
for e in msg:
m+=e
print(m)
@shrewd fjord :white_check_mark: Your 3.11 eval job has completed with return code 0.
bla bla
So how would you change this exactly?
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]```
For embed, altho too old πΏ
Is "u" a class?
Ye
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
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?
This is how it should be displayed:
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)```
wdym by PC
with no ide
You may as well just do
embed.add_field(..., value="\n".join(f"> {u.summoner_name}" for u in team_1)
just double click the py file
You won't need the other 4 lists that way
Pycharm is a IDE, u can use it on pc anyway
Uh...
yes but it uses 2gb ram, and id much prefer to run it in the basic python window when im not working on it
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...
it closes right away when i open it
Dont open it
open cmd promt
And enter the exact file directory on cmd and hit enter
good point i shouldve tried cmd
It should come online right way
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)```
one second
Yeah personally I wouldn't try to make a bunch of other lists
Just do it all in the list comp within the values kwarg
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]```
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

@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
yes yes
i had to do it seperately
for both
but it wont work on regular python
ive tried cmd
This is how it would look like if I didn't use list
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
0|blitzcrank | KeyError: 'member'```
@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'
someone ping me when you have a solution, tyty
jsyk for the future i do not mind pings

How can I extract it correctly?
I'm still not really sure what the datatype of team_1 is
If dict, what's it's structure?
Wonder if that is json data given its League data
Hi, what is the most reliable way to tree sync()? Currently, I'm syncing application commands on on_ready.
setup_hook
Why shouldn't I add {"member": member} key to the dictionary?
Isn't it still bad juju to auto-sync your command tree?
You probably should
Or the user class:
class User:
def __init__(self, ...):
...
self.member = member
that way you can use u.member.mention in your list comp
setup_hook is only called once
So nothing wrong with that
Just searched it, couldn't find what you mean. Can I have further explanation? I'm new to python and using discord.py.
But if you'd like you can have a dedicated sync command
I get that it runs once; it's due in part from constantly restarting your bot during development.
That's the caution.
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def setup_hook(self):
await self.tree.sync()
bot = MyBot(command_prefix="!", intents=discord.Intents.all())
bot.run()
That's right, however it shouldn't matter
Discord has even made it so you can sync your commands only to one specific guild just for testing
In production, however, your bot script shouldn't be restarted so often that the syncing is being problematic
Mhmm that is true. I guess I assumed they were globally syncing.
No yeah, it's fair to assume you'd globally sync in prod and sync to a specific guild in dev

Thank you.
With the type of hosting options people are going for these days it does happen :P
Oh yea.. gotta love those "bot hosting sites for free"
(Looking at you replit)
Well replit should get it's pride kicked out from under it at times
True, it's the user base issues
@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 π
Member doesn't have banner
And thus returning None
!e
print(None.url)
@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'
speaking of banners, how do i make GIF banners work without using two links, one for gifs, and one for PNGs
wich member?
Wait as per docs, you just change the link's extension
Or just u can do...member.banner.url_as or something
Need to check docs
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
member.banner.url.replace('gif','png') altho not recommended
The banner url will always return the exact url
U no need to worry about changing banner url to gif or png
What's the prob?
- why do you use
ctx.message.authorinstead ofctx.author user_bannernot userBanner according to python style guide- you use
x = ...in some parts andx=...in others
'pip' is not recognized as an internal or external command,
operable program or batch file.
python3 -m install pip
wait forgor the cmd idk if it's correct πΏ
what π
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
I forgor π
first of all, it's python on windows not python3 @junior burrow
Demn
pip comes with python, you don't install it
Not always 
Unless some bad installation
I had to install manually π

@junior burrow, does running python work?
Type "
where python
In cmd prompt
what do you mean? do you mean basic python files not in an ide with no imports, yes. it also works with some imports just not discord for some reason
He is trying to run a py file on cmd without IDE
i am, but i would like to run discord.py without the use of an ide
it gave the python.exe directory
@junior burrow your IDE uses a different python installation, probably a virtual environment
Demn, then it's installed 
you will need to install the discord.py package separately
yes
i did, and when i use pip to install it says "requirements already satisfied"
. πΏ
Alr imma head out 
;-;
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)```
is where pip the same as where python
ah wait i forgot pip doesnt work for you
INFO: Could not find files for the given pattern(s).
yeah
either im too high or im js fucking too high but whats da problem w that
The member.banner is returning None bruh
;-;...
not a great idea to code when im stoned ig
Do this.....
if member.banner is None:
return await ctx.send("Seems like you don't have banner lol")```
i thought you were leaving?
so?
u can do it without ide as well
I said so
I said him to do on cmd prompt but he having prob πΏ


!intents
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.
@static sorrel
yeah, here
can someone help me i want that my bot saves the image i send then he sends it back
?
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
Convert it to file then send it back
Please send the error
There are so many things wrong with that
Enable intents
blocking io πΆ
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
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.
I need help
I CAN'T FIX THISS
d! TypeError Client.init() missing 1 required keyword-only arguments: 'intents'
Read the error
!d TypeError Client.init() missing 1 required keyword-only arguments: 'intents'
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").
I did read it
!intents
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.
I can't fix it
Read
What's mandatory?
mandatory means required
if message.attachments:
should i use this?
yes
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
nextcord.Message is the class
You need an instance of the class, which you can get from ctx.message
tysm
And there is no .Attachment attribute for Message
You can see all the attributes in docs
aight thx
how would u fix that?
cuz i cant find the Attributes in the website...
!d nextcord.Message
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.
Go to that link
there is .attachments
.-.
Ok so you can use that
No...
This means you do ctx.message.attachments
thx
Id recommend learning classes in python to understand this
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
and how can i fix it?
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)```
woof
What does that supposed to mean
And why are you using getattr function
someone suggested it a while ago π€·ββοΈ
right. it's safer to use getattr because not all error instances have original attr
but your question is still not much clear
I want it so the missing permission one has the discord ping like the top one
oh
then just ping the user?
@static bane you don't have permission to kick people ( sorry for ping )
Ig π€·
Is there a way I can reply to the user without specifically mentioning them in the message? Or do I have to add {member.mention} at the beginning?
Figured it would stand out more to the person trying to execute the command
There's no other option than to mention them in the response
I see, thank you for helping guys :]
@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
What is the context here 
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(f'cogs.{filename[:-3]}')
Do you know what is this problem?
You need to await the coroutine the load_extension function returns
Can it be because u is a dictionary?
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')
Should I await the client.load_extension?
yes, its coroutine
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")...
does discord.py support slash commands now
all answers on google are from when discord.py was discontinued
it does
ok ty
welcome
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)
@naive briar I tried many things but I couldn't success can you give me an example pls?
I fixed this just by using client.get_channel(channel_id)
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
You mean ping runs forever?
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
commands defined like that don't get automatically added to the bot
that works only in cogs
Yes
I just need the response from the ping...
so that I can then say in an if query whether the server is online or offline
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?
You don't need to
At least we got rid of the lists: team_1_ranks, team_2_ranks, team_1_names, team_2_names
@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?
The former uses a class and the latter uses a regular dict
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
hm
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
property public_flags```
Equivalent to [`User.public_flags`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.public_flags "discord.User.public_flags")
whats wrong w this iont understand
You started a string but never ended it
the string is at the end?
You have to use triple quotes, or use \n to express a new line
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
hi! somebody knows how to get the user id with discord.py?
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```
What is it doing? When you ask questions describe your problem or any related exceptions
Run in debugger and see what the code is doing when that executes
im not getting a error
hi! what is the best hosting website for my bot with GitHub repo ?
i leave in france
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'
Meaning that self.message is a coroutine, something that you have to await
It is
You're awaiting the .edit, not the self.message
Why would self.message be a Coro 
The code is here @vocal snow
any help^
Define the user.
user= ...get_member() or get_user()
Then you can do user.id
You need the id to use get_member/get_user...
with what symbol i write code?
anyway, i get the user id with ctx.author.id, and it work
!code
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.
you mean format?
yeh thanks
There are many free Hosters but the best that worked for me is Astrohosting itβs free but sometimes the Server crashes the you need to restart it and they have a DC where you can ask questions
Thks
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 
UnboundLocalError: local variable 'get_admin_role' referenced before assignment
I can read errors 
then fix it
It is
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)```
π€
How? I do all right ig
Btw nice help
!e
def foo() -> None:
bar
bar = "bar"
foo()
@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
You're basically trying to access get_admin_role which might not be available depending if admin_fetch isnt None
i remember you
!intents
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.
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
Anyone know how to interact with a ticket tool panel using discord api
stop using replit
and use a real IDE or code editor
why whats wrong w replit lol
What's a fake editor
I highly recommend uninstalling that and all other 3rd party libs, dpy supports everything you need
What
Pins
"and use a real IDE or code editor"
something that's on the cloud

TFW when GitHub codespaces (hosted VSCode) isn't a real editor
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?
this is more of a question for #1035199133436354600 or #async-and-concurrency, but it looks like you forgot to put an await in front of your file.write()
reference: https://pypi.org/project/aiofiles/ py async with aiofiles.tempfile.TemporaryFile('wb') as f: await f.write(b'Hello, World!')
alr ill try it
Who would have thought, huh
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?
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'
!d discord.Member.display_avatar
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.
ah ok thank you
You're welcome
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?
Please avoid crossposting, your question is already being answered in #python-discussion
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)
is it possible to send an embed image as a spoiler?
await bot.get_partial_messageable(CHANNEL_ID).get_partial_message(MESSAGE_ID).reply(embed=emb)
thank youu
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?
This is going to be a lot more complicated than you think
Sounds great!
Where can I start? 
I would not recommend tackling unless you 110% sure you know what you're doing and you're fairly advanced
Hmm...
That sounds.. painful.
But I've got time to learn
Look into PIL or Pillow, if your image is static (e.g it will always be the same image every time), you could apply a hue transformation to a specific part of an image (e.g the region surrounding a cup of coffee)
And this.. Pillow will be able to do both the examples I provided above?
It will be able to!
Thanks, Robin!
Always helpful 
thank
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?
still need help π
no tracebacks?
yeah
Do u have a error handler?
no
try removing msg2 line
One liner found 
Just learn the docs
where do i host my discord bot
A VPS
It's not really a good way to store data that constantly changes but can be calculated. Store only the time when user's progress started being tracked, then you can get how many seconds have passed by subtracting it from current time
If it's open-source you can find it on github
Yeah i think i did something along the lines of round((datatime.datetime.now() - member.joined_at).total_seconds, 0)
what bout a phone
what do you mean?
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?
can you use rich presence for the change_presence for a bot? or is it not possible?
Are you just asking if you can copy paste code and have a discord bot work?
Wouldnβt timezones be an issue there?
No
Just simple playing, watching, blah blah blah.
Possibly
!d discord.utils.utcnow
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.
Are you sure? Iβm not sure if thatβs actually true.
This is what I have
f"{datetime.datetime.utcnow() - member.joined_at.replace(tzinfo=None)}"
Not sure if that's needed or not though 
using a unix timestamp is far better
no just view discords bot code like you can view javascript on website through inspect element etc
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
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
why is that?
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
How can I check if a string is an emoji within a slash command?
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)
thats not how you do it
!d discord.Asset.save
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.
!d discord.ext.commands.EmojiConverter.convert
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.
use this to try converting the string to an emoji
I was told to use partial emoji converter
:0
Unless the bot owner is willing to give the code or just hack the owner's acc 
okk
Ahhh, thanks Vanessa!
has it worked?

Sus emoji name
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


