#discord-bots
1 messages · Page 369 of 1
Hi guys,
2024-05-26 16:30:09 WARNING discord.gateway Shard ID None heartbeat blocked for more than 10 seconds.
Loop thread traceback (most recent call last):
File "/home/container/bot.py", line 232, in <module>
bot.run_bot()
File "/home/container/bot.py", line 181, in run_bot
self.run(self.discord_token)
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 860, in run
asyncio.run(runner())
File "/usr/local/lib/python3.11/asyncio/runners.py", line 190, in run
return runner.run(main)
File "/usr/local/lib/python3.11/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 641, in run_until_complete
self.run_forever()
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 608, in run_forever
self._run_once()
File "/usr/local/lib/python3.11/asyncio/base_events.py", line 1936, in _run_once
handle._run()
File "/usr/local/lib/python3.11/asyncio/events.py", line 84, in _run
self._context.run(self._callback, *self._args)
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/bot.py", line 34, in on_ready
await self.check_products()
File "/home/container/bot.py", line 44, in check_products
response = requests.get(store_url + "products.json?limit=250", headers=headers)
File "/home/container/.local/lib/python3.11/site-packages/requests/api.py", line 73, in get
return request("get", url, params=params, **kwargs)
File "/home/container/.local/lib/python3.11/site-packages/requests/api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
File "/home/container/.local/lib/python3.11/site-packages/requests/sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
File "/home/container/.local/lib/python3.11/site-packages/requests/sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
File "/home/container/.local/lib/python3.11/site-packages/requests/adapters.py", line 589, in send
resp = conn.urlopen(
File "/home/container/.local/lib/python3.11/site-packages/urllib3/connectionpool.py", line 793, in urlopen
response = self._make_request(
File "/home/container/.local/lib/python3.11/site-packages/urllib3/connectionpool.py", line 537, in _make_request
response = conn.getresponse()
File "/home/container/.local/lib/python3.11/site-packages/urllib3/connection.py", line 466, in getresponse
httplib_response = super().getresponse()
File "/usr/local/lib/python3.11/http/client.py", line 1395, in getresponse
response.begin()
File "/usr/local/lib/python3.11/http/client.py", line 325, in begin
version, status, reason = self._read_status()
File "/usr/local/lib/python3.11/http/client.py", line 286, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/local/lib/python3.11/socket.py", line 706, in readinto
return self._sock.recv_into(b)
File "/usr/local/lib/python3.11/ssl.py", line 1314, in recv_into
return self.read(nbytes, buffer)
File "/usr/local/lib/python3.11/ssl.py", line 1166, in read
return self._sslobj.read(len, buffer)```
this error is due to a network error or what ?
i keep getting error like that every 5-10 minutes
You have blocking code somewhere most likely
are you using time.sleep at all
no
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
- The standard async library -
asyncio - Asynchronous web requests -
aiohttp - Talking to PostgreSQL asynchronously -
asyncpg - MongoDB interactions asynchronously -
motor - Check out this list for even more!
my bot send an embed when a new item or restocked item is available on Taylor Swift store, i use requests for doing the request of the json file
i need to change with aiohttp ?
you use the requests library?
yes
aiohttp directly return the json ?
because with requests i was doing like that
async def check_products(self):
while True:
for store in self.stores.keys():
try:
store_url = self.stores[store]['url']
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
}
response = requests.get(store_url + "products.json?limit=250", headers=headers)
#print(f"Response: {response.text}")
current_data = response.json()
shop_name = self.stores[store]['name']
i = 0
for product in current_data["products"]:
i += 1
print(f"Found {i} products at {shop_name}, Date: {datetime.datetime.now()}")
if self.previous_data[store] is None:
self.previous_data[store] = current_data
await asyncio.sleep(15)
continue
new_products = self.get_new_products(current_data, store)
restocked_products = self.get_restocked_products(current_data, store)
self.previous_data[store] = current_data
for product in new_products:
available_variants = []
for variant in product["variants"]:
if variant["available"]:
available_variants.append(variant)
if available_variants:
await self.send_new_product_embed(product, available_variants, store)
for product_id, variants in restocked_products.items():
product = next((p for p in current_data["products"] if p["id"] == product_id), None)
if product:
await self.send_restock_embed(product, variants, store)
except Exception as e:
print(f"Error fetching or processing data: {e}")
ShopBot.log_to_file(f"Error fetching or processing data: {e}")
pass
await asyncio.sleep(15)```
youll only have the modify the code slightly to use aiohttp
if i replace the
response = requests.get(store_url + "products.json?limit=250", headers=headers)```
with that
```py
response = await aiohttp.ClientSession().get(store_url + "products.json?limit=250", headers=headers)```
its good ?
try it
i have do that directly and he work
current_data = await self.fetch_data(store_url + "products.json?limit=250", headers)```
```py
async def fetch_data(self, url, headers):
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
return await response.json()```
work fine on my pc and work fine on my pterodactyl
thanks for the help
Because it does not work?
code: ```py
async with aiohttp.ClientSession() as session:
try:
async with session.get("https://minecraft.com/", proxy="https://103.255.145.62:84") as response:
print(f'Response status: {response.status}')
if response.status == 200:
data = await response.text()
print('Data received')
except aiohttp.ClientError as e:
print(f'HTTP error: {e}')
except Exception as e:
print(f'Unexpected error: {e}')``` error: error: Starting HTTP request...
HTTP error: Cannot connect to host 103.255.145.62:84 ssl:default [Connect call failed ('103.255.145.62', 84)]
show the whole of the traceback
that's all
I see
use #1035199133436354600 you'll get help faster there
I mean, the error pretty much says it all.. It's unreachable
!d discord.User.mention
property mention```
Returns a string that allows you to mention the given user.
Made a bot that pings myself 147 times

!e s
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | s
004 | NameError: name 's' is not defined
!e
import requests
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | import requests
004 | ModuleNotFoundError: No module named 'requests'
!e
import urllib3, urllib
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | import urllib3, urllib
004 | ModuleNotFoundError: No module named 'urllib3'
!e
import urllib2
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | import urllib2
004 | ModuleNotFoundError: No module named 'urllib2'
!e
import os
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
!e
import subprocess
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
!e
import subprocess
print(subprocess.check_output("apt -v").decode())
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | print(subprocess.check_output("apt -v").decode())
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/lang/python/default/lib/python3.12/subprocess.py", line 466, in check_output
006 | return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/lang/python/default/lib/python3.12/subprocess.py", line 548, in run
009 | with Popen(*popenargs, **kwargs) as process:
010 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/IAKRYVZJI7RCMXWLW4HHUDPK6A
!e
import subprocess
print(subprocess.check_output("apt -v", shell=True).decode())
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | print(subprocess.check_output("apt -v", shell=True).decode())
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/lang/python/default/lib/python3.12/subprocess.py", line 466, in check_output
006 | return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/lang/python/default/lib/python3.12/subprocess.py", line 548, in run
009 | with Popen(*popenargs, **kwargs) as process:
010 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/4LMWS4DFSHVNYBSPXAA6B6JJ4U
!e
print("open" if import("requests").get("https://httpbin.org/ip").status_code==200 else "closed")
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print("open" if __import__("requests").get("https://httpbin.org/ip").status_code==200 else "closed")
004 | ^^^^^^^^^^^^^^^^^^^^^^
005 | ModuleNotFoundError: No module named 'requests'
!e
print(import("subprocess").check_output("curl"))
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(__import__("subprocess").check_output("curl"))
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/lang/python/default/lib/python3.12/subprocess.py", line 466, in check_output
006 | return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/lang/python/default/lib/python3.12/subprocess.py", line 548, in run
009 | with Popen(*popenargs, **kwargs) as process:
010 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/TCDJ4ICWJAI7IWYIC55UEMUYCI
!e
print(import("subprocess").check_output("curl",shell=True))
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | print(__import__("subprocess").check_output("curl",shell=True))
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/lang/python/default/lib/python3.12/subprocess.py", line 466, in check_output
006 | return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
007 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
008 | File "/lang/python/default/lib/python3.12/subprocess.py", line 548, in run
009 | with Popen(*popenargs, **kwargs) as process:
010 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/SNSIS2FNP2VG2RRCBZFLBAMR5I
!e
print(import("os").system("whoami && id"))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
32512
!e
from threading import Thread
def wait():
import("time").sleep(100)
for _ in range(5000): Thread(target=main).start()
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 6, in <module>
003 | for _ in range(5000): Thread(target=main).start()
004 | ^^^^
005 | NameError: name 'main' is not defined. Did you mean: 'min'?
!e
from threading import Thread
def wait():
import("time").sleep(100)
for _ in range(5000): Thread(target=wait).start()
:x: Your 3.12 eval job timed out or ran out of memory.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 6, in <module>
003 | for _ in range(5000): Thread(target=wait).start()
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/lang/python/default/lib/python3.12/threading.py", line 992, in start
006 | _start_new_thread(self._bootstrap, ())
007 | RuntimeError: can't start new thread
!e
def wait():
import("time").sleep(100)
for _ in range(5000): import("threading").Thread(target=wait).start()
:x: Your 3.12 eval job timed out or ran out of memory.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | for _ in range(5000): __import__("threading").Thread(target=wait).start()
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/lang/python/default/lib/python3.12/threading.py", line 992, in start
006 | _start_new_thread(self._bootstrap, ())
007 | RuntimeError: can't start new thread
!e
def wait():
import("time").sleep(100)
for _ in range(50000): import("threading").Thread(target=wait).start()
:x: Your 3.12 eval job timed out or ran out of memory.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | for _ in range(50000): __import__("threading").Thread(target=wait).start()
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | File "/lang/python/default/lib/python3.12/threading.py", line 992, in start
006 | _start_new_thread(self._bootstrap, ())
007 | RuntimeError: can't start new thread
You good?
how would I see who the user pinged from a slash command?
@client.hybrid_command()
async def requesthelp(ctx: commands.Context, user: str):
I thought this was a channel for bots, mb
Channel sidebar is to the left, members list to the right. What is the middle part called?
that's a forum channel
And the one to the left is called forum channels sidebar?
what, that's just the guild's channels list
why do you want to know that
if you want to manage a forum channel with your Bot you just need to know the channel type, which is forum
Can someone help me with my bot command? HMU
yo guys, what is a cheap way yall host your bots online?
im thinking replit but 10 dollars a month is a lil much for me
replit is not made for running bots. It was designed for hosting web code. It is extremely unfit for purpose, especially at that price
import discord
from discord.ext import commands
from discord_components import Button, ButtonStyle
import json
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
CHANNEL_ID = 1243242699298050138
ganhador = 1066493326636884039
hild = 1243240307147931672
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
await send_giveaway_message()
async def send_giveaway_message():
channel = bot.get_channel(CHANNEL_ID)
if channel is not None:
embed = discord.Embed(
title="Legacy - Sorteio",
description="🎁 Sorteio de **R$150,00** reais!\nPode ser resgatado em pix ou em gift no site.\n\n**Requisitos:**\n- Ser verificado no servidor, para verificar vá em [#1243242699298050137](/guild/267624335836053506/channel/1243242699298050137/)",
color=0x8E3CC6
)
embed.set_image(url="https://media.discordapp.net/attachments/1243447988039323678/1244403998006710352/sorteios.png?ex=6654fd09&is=6653ab89&hm=241bac3604f8a79514a394d3aef3ae6d729c826756ade767cf953e9591ab9ed4&format=webp&quality=lossless&width=810&height=309")
embed.set_footer(text="© Todos os direitos reservados.")
button = Button(style=ButtonStyle.primary, label="Participar do sorteio", custom_id="join_giveaway")
msg = await channel.send("@everyone Expira em <t:1716769560:R>", embed=embed, components=[button])
message_id = msg.id
await msg.add_reaction("🎁")
@bot.event
async def on_button_click(interaction):
if interaction.custom_id == "join_giveaway":
user_id = interaction.user.id
try:
with open("ids.json", "r") as file:
ids = json.load(file)
except FileNotFoundError:
ids = []
if user_id in ids:
ids.remove(user_id)
await interaction.response.send_message("Você agora não está mais participando do sorteio!", ephemeral=True)
else:
ids.append(user_id)
await interaction.response.send_message("Você agora está participando do sorteio!", ephemeral=True)
with open("ids.json", "w") as file:
json.dump(ids, file)
bot.run('meow')
@young daggercan u help me out?
the buttons are not working
discord_components is a bit outdated last I recall. Whatever discord wrapper you're using should support buttons tho
Yo so uh i know this isnt replit dc server but there invite is paused soo imma asked here
How do i fix
Hmm... We couldn't reach this Repl
Make sure this Repl has a port open and is ready to receive HTTP traffic.
Make sure the script is making the HTTP server correctly
So how do i do that
Discord.py template yes
And using replit
...user: discord.User): or discord.Member if you want the user as a member, only works in guilds btw otherwise it going to give a discord.User object
Or use both
!e
code
!e import discord.py
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | import discord.py
004 | ModuleNotFoundError: No module named 'discord'
:x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 5, in <module>
003 | import discord
004 | ModuleNotFoundError: No module named 'discord'
:incoming_envelope: :ok_hand: applied timeout to @limber jolt until <t:1716793027:f> (10 minutes) (reason: newlines spam - sent 106 newlines).
The <@&831776746206265384> have been alerted for review.
!unmute 1228732555591684208
:incoming_envelope: :ok_hand: pardoned infraction timeout for @limber jolt.
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Use our pastebin
Thanks.
Ok.
ah, you can't run a bot using eval
it's a sandboxed environment with networking disabled
we also dont have d.py installed in the environment
Alright.
do you know any other sites that I could use to host a bot?
Take your pick of the ones that just give you ssh access to a machine only you're on, with a dedicated IP. Really it's based on the resources you need
do you have any recommendations
I'd recommend starting by profiling your bot and getting a sense of its resource usage. That said, I and many I talk to use Hetzner as a low cost entry point.
And to be clear, these are VPS's where you go into a machine and set it up via SSH. They aren't "sites". There are some options with a web interface on top of them but they charge you a premium as such.
Digital Ocean, scalable droplets
Only for free, or you can paid ?
I'd prefer paid options that are better, but my price range is only like 1 to 5 dollars a month
.
There is a website called Render, which is used for cloud application housting
There are a free, and paids options
I use it personally for my discord bot
However, it only accept source code coming from Github
Why does this not work?
it doesnt even print any error or something and my bot has the permissions
doesn't exist
only on_guild_channel_create is a valid event so you'll need to check the channel's type there
thx
oops
does it have to be a public page?
If a vps doesn't just give you ssh access to do whatever you want, it's a scam
I wonder what this does lmfao
Even for stupid skid meme code this is just dumb
fr
who even tries to nuke a server anymore
Plenty of shitty little kids with nothing better to do
fr
I was curious how hard it would be to do it, so I just did it and im scared how easy it is now
No, it can be a private repository
Does anyone know why this happens?
wrong server lol
discord.gg/djs
npm install failed
it shouldn't be how you're doing it
you'll get blocked
im not using it for anything lmao dw
I dont recall ordering a yapachinno/j
How do I set cooldowns to slash app commands?
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown) is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
how do i actually draw a heart? tried 10 times :3
tf
you can use a premade png which has already an heart in it
with PIL you should just put things that are dynamic, so the % and the user images
these are resource expensive operations so you should limit them as much as possible
who said it was a premade image?
you can use a premade image with heart and add avatars to it.
it nottttt
i suggested to use a premade image as base
ohhhhh
.
mb ty
and if u want nitro just pretend to be a girl and use :3 and ;3 and make your words looonger 💀
UwU, ty! ;3
Bros so desperate UwU :3 >.<
@app_commands.command(name="banner", description="Muestra el banner de una persona")
@app_commands.guild_only()
@app_commands.describe(user="el usuario a mostrar")
@app_commands.checks.cooldown(1, 10, key=lambda i: (i.user.id))
async def banner(self, interaction: discord.Interaction, user: discord.Member = None):
try:
user = user or interaction.user
user = await self.bot.fetch_user(user.id)
embed = discord.Embed(title=f"Banner de {user.name}", color=0xD1C55A)
embed.set_image(url=user.banner.url)
await interaction.response.send_message(embed=embed)
except AttributeError:
await interaction.response.send_message("El usuario no tiene banner.", ephemeral=True)
except Exception as e:
await interaction.response.send_message(f"Error: {e}", ephemeral=True)
@banner.error
async def on_banner_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
await interaction.response.send_message(str(error), ephemeral=True)```
When I execute the command 1 time it works, but the 2nd time the cooldown is not working and the app does not respond
u mean b4 cooldown ends?
set an else statement for ur error handler to see if its being eaten up
:v
Hey, guys I'm creating my first Discord bot and I am planning to implement it into a free company that me and my friend created (Free company is a guild in any other mmao) is there any security things I need to worry about since we are going to be recruiting random people at first? if so, what should I try to implement and research to protect the bot and my system?
also why does ur command have self but error handler has no self as first arg?
what does ur bot do?
alr
Just allow you to look up information about the game. Here is an example of a mount search. I am planning to add more features later. But I would say, I am not planning to add any feature that a mod can do. For example, banning people, muting people, etc.
The mistake was that I forgot about self as the first argument of the error
ic glad we caught it

then u should be all good lol
Someone know how can i check who use my modular select menu i want only 1 people can use it
This is what i call modular select menu:
I have to add else: raise error in all the commands of my bot? and there is no system or something that is global?
startup > ADDITIONAL PYTHON PACKAGES > nextcord
in your host
How do I uninstall discord.py in it?
https://paste.pythondiscord.com/GHLA
Why could config be taking so long to pull the data..?
I use supabase as my database host, and it postgresql. Just curious if its my code or maybe the database. Yeah the code might be a little bad. But thats why I am asking 😁
nvm I fixed the issue... un optimized code. Went from 3 seconds to less than a second.
So, how come I get this error
In components.0.components.2.url: A url is required
on this line:
await ctx.send(embed=embed, view=view)
where view is an instance of this class:
https://pastebin.com/DSA4TPS1
It needs the url
Yeah, thanks, figured the issue out. I was using a link button but in reality I just wanted a grey one
2024-05-27 16:35:44 WARNING discord.http Global rate limit has been hit. Retrying in 0.30 seconds.
2024-05-27 16:35:44 WARNING discord.http We are being rate limited. GET https://discord.com/api/v10/channels/1156177041528463432/webhooks responded with 429. Retrying in 0.30 seconds.
2024-05-27 16:35:44 WARNING discord.http Global rate limit has been hit. Retrying in 0.30 seconds.
2024-05-27 16:35:44 WARNING discord.http We are being rate limited. GET https://discord.com/api/v10/channels/1156177041528463432/webhooks responded with 429. Retrying in 0.30 seconds.
2024-05-27 16:35:44 WARNING discord.http Global rate limit has been hit. Retrying in 0.30 seconds.
2024-05-27 16:35:44 WARNING discord.http We are being rate limited. GET https://discord.com/api/v10/channels/1156177041528463432/webhooks responded with 429. Retrying in 0.30 seconds.
2024-05-27 16:35:44 WARNING discord.http Global rate limit has been hit. Retrying in 0.30 seconds.```
Is there a way to like, fix this?
or should I not worry about this?
is there a specific command you're running that causes this?
And why I am asking is because, this is the ONLY channel out of my entire bot database that has this issue. and its THIS channel. There is over 150 entries
Its a logging system. But still, there is no way this is the only server that has this issue..?
Well, youre exceeding the api ratelimits, so you should change your bot's functionality to efficiently run operations
for example, if you're logging in a discord channel, use webhooks
Can you not read...?
/v10/channels/1156177041528463432/webhooks
oh I'm sorry.
💀
you should probably try a different logging method in case your bot is used by many people
are there any loops/repeated actions that could be causing this?
would be my guess.
@vapid parcel
Nope
it would be happening in other servers too
Not only 1
fair point.
Okay.
So I found the issue.
allowed_event_types = {"member_event", "message_event", "server_event", "voice_event"}
These are my event types. Basically, I have a function to make a webhook. But if a webhook was made and it was in the same channel but to different event, they would use the same webhook. So I made each webhook have their own name! So now it won't have a rate limit I think, so now it will be better later on. But that should fix the issue!
Would anyone be able to point me to a working example of how to set up extensions or cogs with slash commands using discord.py? I can't seem to find a solution.
I currently have my bot working using cogs but with prefixed commands, and want to switch over
It's very similar: instead of using discord.ext.commands.command decorator, you use discord.app_commands.command
!d discord.app_commands.command
@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
thanks, that seems to be working. Now should I be syncing the tree in every cog, or once after all cogs have been loaded?
once all cogs are loaded
awesome, thanks for the assistance
@unkempt canyon
#bot-commands please
This is a discord bots support channel
Hey, tried using the search function, but I seem to be unable to create a discord bot and then private it? They've changed stuff aroudn and I'm a tad bit confused, I end up with this error message:
Private application cannot have a default authorization link
Anyone know how to get around this?
Right because it's private. So only, the app owner (or team devs) can invite it, so the concept of adding a default authorisation link doesn't really make sense.
(that is to enable the "add app" button in the user profile. For who? nobody can add it)
So what does my custom invite link have to be?
If I want to keep it private, how do I go about that
You can still make invite links
Just not set them to show in your bot's profile
@storm leaf Do you mean going to Oauth2 > Redirects for enabling a redirect uri after the invite flow?
But I have no redirects at all
Just shows "add redirects", not to change any existing ones
I just created a new app, didn't change anytrhing, tried to set intents and disable it from being public
And it's not letting me 😂
Show please (a screenshot) (im confused)
What happens when you set it to private?
Try going to installation and disabling that shit
Install link [...] None
Just tested it, should work
Yeah
Aah you're a legend
that's the setting for this button https://leo.might-be.gay/QC6LHG.png and if you have it enable it, you can't private it
Tyvm, fuck sake
Yeah it's very annoying, tyvm sir
np
saved me a couple of hours 😂
Hey bro, last question: I noticed that even if I remove some of my optional commands to my slash command, so for example going from having:
/test command1 command2 command3
to:
/test command1 command2
The 3rd one still remains, I remember something about having to sync the commands? Is that still a thing, would you know?
Yes you need to sync your command tree to inform discord about your local changes
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
Is there a "fuller" example of this?
Yeah I'm doing something wrong, but I'll look into it, thanks! 😄
mine prints errors, tried searching around here, everyone seems to be doing it differently. Can I throw it on my "on_ready?"
You can but you shouldn't
Yeah there are a bunch of different things in here, I've been trying to find one but I haven't touched python for like 2 years 😂
How often do you need to tell discord hey I've updated my commands! not that often. And it's pretty rate-limitey to sync
You usually just have a message command to sync
Can I just make another slash command to sync my new commands?
Or did I misunderstand you
I curated and created a pretty full-featured command for syncing your CommandTree, you can see it here:
well say you make a new bot, you have to go in the code and type a sync for the initial syncing
then remove it so it doesn't keep doing that
seems kinda cumbersome. Also you can't have owner-only slash commands, so yay message commands
Could technically limit it to specific ranks?
yea but that sounds annoying
where do you guys host the bots? i made a code but there’s a lot of options im looking at
Options will vary based on your needs. Some red flags to look for:
- Anything that markets itself as a "bot host" is probably scamming you, there's no such thing as a bot host and generally these are to lure in the uninformed
- Anything that's "free"
- Anything that restricts your ability to ssh and do whatever you want. If it insists you go through a panel, that's going to limit you
Visual studio code
Fr
how couldnt have i thought of this, genius
why am i getting an error??
still not working
its already satisfied
@arctic zodiac
tf is pytoileur
i think hes tryna hack me or sum can you help me
yeah, definitely don't install that
there are some typos in your code that probably causes the error
@wanton current i already installed it i removed it though
can you help with my error possibly
!cban 1213823510439264297 spreading malware
:incoming_envelope: :ok_hand: applied ban to @arctic zodiac permanently.
wait am i gonna get hacked
you probably already have been
i only installed it on my visual studio code, why is he just allowed to tell me to do that?
shouldn't it be blacklisted or something.
malware gets blacklisted once someone notices it
ban also didn't work on him
this one wasn't noticed yet, it seems
Also can you send the full error?
did you install discord.py
yes
you should immediately change your discord password, and any other important passwords you have
Aoba seus gringos
from a different device
Sou brasileiro seloko
^ @slate swift
can i chane my passwords on my pc?
you should use a different device than the one that the malware was installed on
i thought he was legit because i didnt know there was malware in the pips that people could make :/
you should remove the text C:\\Users\\{yourusername}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\System86 directory and the ```text
C:\Users\{yourusername}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\Runtime.exe
both of those are malicious
and if the runtime.exe process is still running, you should kill it, too
it's hard to know what that thing did to you, though
to be safe @slate swift you should change all of your passwords from another device, and then reinstall your OS on the device that got hacked
wait what?
when you installed the malware, it should have created that executable and that directory
do i open the the command prompt or what
you can remove them however you normally remove files
the cmd prompt is fine if you're comfortable doing it that way
I'm assuming you installed this on a Windows machine?
mhm
yeah, so it very likely infected you successfully, then
Please someone help me
App commands is from discord import app_commands
@winged forge @merry cliff neither fixed
from discord import app_commands
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents = discord.Intents.default())
@bot.event
async def on_ready():
print('bot is online')
print('-------------')
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)}")
except Exception as e:
print(e)
@bot.tree.command(name='test')
async def test(interaction: discord.Interaction):
await interaction.response.send_message(descripton='test {interaction.user.mention}')
@bot.tree.comamnd(name='host')
@app_commands.describe(thing_to_host = "What should I host?")
async def host(interaction: discord.Interaction, thing_to_host: str):
await interaction.response.send_message(f"title={interaction.user.mention} Is Hosting!", description=f"Type of game: {thing_to_host}")
bot.run("my tokennn")```
Is there a specific error?
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Oh
pip install discord
try it in console
i already did thats the thing
pip install -U discord.py
Do you have multiple python versions?
dont forget .py
how do i check
try this
pip install -U discord.py
says pip isnt recognized
Discord is a mirror library so it doesn’t really matter
py -0
orignally the ms store
i deleted it from my settings
and redownloaded from website
send image when u try pip install discord
!pypi discord
A mirror package for discord.py. Please install that instead.
Released on <t:1691703907:D>.
It’s literally a mirror package
for check if u downlaod 'pip' or no
????
@merry cliff what should i do?
Try py -m pip install -U discord
Did it work?
TYSM BRO
havent made a discord bot in a couple years, was wondering what the most recent way to make a music bot is
one that you search up a vid and it provides a corresponding youtube vid's music in vc
ITS FUXED
No problem
I wouldnt create one unless you're doing it for self use because it will get taken down quick
Yeah
You spelled "description" wrong
I want to make a slash command in discord.py, but I'm not sure how to do this type
So i want to have 3 options and when someone clicks that option that has a specific role they can input something and it will send
could anyone help me with this
Should I put else: raise error in all my bot commands? Is it advisable?
It was reported a few days ago, PyPI 😩
for me mm/dd/yyyy
But thats just Americans right..?
Everyone else uses DD/MM/YYYY i think..?
on the contrary it says the malware was only published last evening, about the same time as right now
https://en.wikipedia.org/wiki/List_of_date_formats_by_country
seems like it, but ultimately you'll find someone that prefers a different format
but you can be grateful that you don't need to guess the format between DD/MM/YYYY or MM/DD/YYYY 🥴
I will just use DD/MM/YYYY
if someone wants to complain, then thats on them 
Im used to MM/DD/YYYY but I know majority of the world uses DD/MM/YYYY so I am going to use that...
as long as its in your prompt, it shouldnt be too confusing
date picker component when 
wonder how dateparser disambiguates between date formats...
thats what i use for my reminder command, along with autocompletion to tell the user exactly what datetime was interpreted before they submit it
how do i change the displayname of my discordbot in the server
like the bot's guild nickname? get your bot's member object for that guild with Guild.me, then pass nick= when using Member.edit()
a randomized birthday gif maybe? also do you know the user's timezone? the timing might be off if they're ahead of your bot's system timezone
I have the timezone off
Because I have no clue on how I wanna do all of that 😭
I could use pytz or whatever its called
pytz is deprecated since zoneinfo got added to the stdlib in 3.9
https://docs.python.org/3/library/zoneinfo.html
(but on windows you need tzdata installed for it to work correctly)
so don't use pytz..?
if you have 3.9+, use zoneinfo instead
oh damn..
alr
So this is my idea... idk if its good or not... but you can judge if its good or not basically..
I will store their time but in UTC form. so I know when to send them a message..? but in utc..?
So I would convert their time from whatever to utc
Making it easier for my task to understand stuff
whats the best code for making slash commands
hmm, what if the user moved to another country?
bot.tree.command? or something else
we have a command to delete their data if they wanted
they can delete it, then remake their stuff
discord.py, disnake, and nextcord all have different implementations of slash commands, so you might want to look through each of their github examples
It depends on what you are wanting to do, there is no best.
like buttons
though afaik discord.py's still the most popular from the rest, so you're probably most likely to get support for it here
Buttons don't require slash commands. That would require interactions.
i know, i have code for buttons
message components are implemented almost the same between dpy and its forks
Are you wanting to keep prefix commands?
but still have slash commands?
or are you wanting to only have slash commands and no prefix commands?
fair enough, only hard part then is making sure they don't forget to update their time...
Well I would have a link in the instructions where to get timezones
my bot has a fairly simple implementation to ask for the user's timezone to use as context in my reminder command, but it still feels a bit awkward having them type out the timezone name after finding it on a website (huh, looks like the timezone map got a nice visual update)
https://github.com/thegamecracks/thegamebot/blob/v2/bot/cogs/timezones.py
First I have to find a good link
and look at you saving the day again 😭
welp, my plan is to take their time and turn it into utc
I’m having trouble with a beautifulsoup call.
In my local environment, it scrapes for all the necessary data im needing. But when I try to run the application on a server, my array returns empty. Assuming it’s not scraping all the same data it is on my local machine.
print out the data once to see if it is what ur expecting
I set it up!
I get memberid, birthday, check if message is sent, UTC_timezone, and their timezone, but I convert their timezone to UTC
and it works fine! Thank you for helping me with the Timezone stuff.
supabase 
Fr 😭
also took thegamecracks idea on the gif stuff.
I have no clue what else to add to the birthdays tho, if anyone has ideas, lmk!
a birthday wish command maybe where users across servers can wish a person and ur bot creates a compendium or memory album of sorts like snapshots of these wishes
Wdym?
basically say a,b,c wish a person d birthday on year 1 ur bot stores these messages and attachments and compiles them into albums or snapshots yearwise kinda like google photos does the user can now go thru this album when he wishes too
supabase has a blob store
For images?
yeah any files
open the panel on left side check the bottom in buckets
if not u can always use discord as a file store
They expire remember XD
yeah 1 year right?
cron job time
altho i can still see images which i have sent long long time ago wonder how that expire works
ah
Unless im behind..?
haven't messed with attachments in a long time
how does that work? does that mean I can't see images sent 24+ hours ago?
prolly some cdn stuff
No.. idk how they do it... I think the links get refreshed inside of discord, but external ones don't.. because so many websites used discord as a image host back then like asher literally just mentioned lol.
So discord was spending so much money, so they had to change it
So I don't know how it truly works, but they do something in discord so images don't expire but externally they do.
ah i see
But don't quote me on that, I could be completely wrong.
but in ur case ur using it internally itself right
so it should work right
try it lol
Yes and no... its weird how they do it 😭
cuz when I resend that link, that link will be expired, but the ones inside of discord, were edited I think..?
they prolly check for incoming host request to their cdn
if its present in a whitelist
Idk how it really works, its really wonky
they maintain
its fucking weird tho. Its smart how they do it tho
cuz they are saving HELLA money rn
no idea lol i gotta look into it
Got any other ideas tho?
maybe some command like birthday --random which gives a random persons id whose birthday is today? endorse them via the bot to send birthday wishes? idrk lol think of some cool interactive features
try to avoid generic stuff, attempt to conduct safe interaction or initiate interactions some how
Someone gave me these ideas
which are cool ideas
thats cool too
I have a question, if I wanted to setup a blacklist system in my bot, that would be like a global check for all commands, how would I do that?
Like the global check part..?
Yes but it raises an error each time.
Hey, what's the decorator to make a slash command admin only?
aaand what's the error
!d discord.app_commands.default_permissions
@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.
When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.
Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.
This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Alright, finished my blacklist system a long time ago.. just never tested it lol. But can others rate it to tell me if I could improve anything..?
nice logik
How to add this changing bio to discord bot?
I wanna add QBit there
so it will be visible at first glance

WATCHING QBit?
!d discord.Client.change_presence - call this with the stuff you want
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter...
okay
await bot.change_presence(activity=discord.CustomActivity(name='QBit'))
would also be a solution for your wish
If it's just one presence you want to set during start up, you're better passing this into your bot constructor rather than calling change_presence
I know more about bots than basic Python
same 
ppl say I need to learn basic Python before i do bots
Congrats, that means you know Python
Discord.py is python, haha
This isn't supported officially by the api docs, they don't want bots doing this yet, so I doubt you'll get help here or anywhere reputable
You should also not be using requests in an async environments
Bro took it personalny and repeats it everyday
@discord.app_commands.command(name='see_requests', description='see current requests')
async def see_requests(self, interaction: discord.Interaction):
requests = self.get_requests()
embed = discord.Embed(title='__Current Plex Requests__', description='', color=discord.Color.blurple())
embed.add_field(name='', value=requests, inline=True)
await interaction.response.send_message(embed=embed, ephemeral=True)
can anyone help determine why im getting yelled at for this?
it runs, and seems to be fine according to documentation
This is a Pycharm issue and safe to be ignored, there's apparently a plugin to use Pyright over the pycharm typechecker which I would recommend
Pycharm typechecks is uh... hot doo doo
lol
Exactly 👍
just have gpt do everything for you. Cant fail
😐
?
!rule 10
i was only joking, i'm sorry
i find your commands are nice! so good function behind them
Oh ok
Anyone have ideas how I could improve?
Good music.
the permanently banned members are saved in a file, right?
In a db.
👍
is there a way that i can set my personal status to something on discord, and have interactable buttons that like send me a notification or somthing like that, here is an example status (ripped from my friends profile who uses clientmods to change his activity status)
ik its not discord bot related but this is a discord channel so i thot it was fine ig
yes there is using applications iirc, games do it, etc
Is that the same as rich presence?
Yes
I have one on mine.
You can either use a client, or use a third party app, which I recommend the third party app because it has more options.
My discord bot for chatbot: https://discord.com/oauth2/authorize?client_id=1237175421917724814&permissions=40115019135808&scope=bot+applications.commands
who can add on servers to help
made in Python and by Brazilians for Brazilians
it was made in pure python and the host is on my PC
I recommend reading his profile before trying to use
Your goal is to be as humanized as possible, this includes:
He reacts to some messages with emoji.
Responds to some messages when he wants.
It sends images, generates responses, enters a call. He also responds privately. It "remembers" people, for example, if you have it on 2 servers and bring up a subject on the first, it continues the subject on the second "remembering" the conversation and who you are, which makes it more humanized.
I have a question on how I could do 1 simple thing.
Say someone wanted to request all of their data from my bot, is there a way I could make a command do that..? and put it in a file..? or would someone manually have to do it..?
Just fetch all the data you're storing from the database related to the user?
thanks
soo.. how we all doing today?
Hey, could you tell me where to place this line of code here github
Better than what?
Doing good.
I am facing difficulty
Earlier
resolved
@ancient stump I placed that here
in events.py
if the activity has to be the same throughout the process you can use the activity in your bot constructor instead of here
!d discord.Client
class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
async with x Asynchronously initialises the client and automatically cleans up.
New in version 2.0.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).
ok, what does it mean?
for example if you always want to display QBit
You can simply set the activity in your bot constructor
commands.Bot(..., activity=CustomActivity())```
Now I have 1 question, so when someone requests their data, its obviously gonna show my tables in a way because its going off tables. Should I really worry abt that?
Example:
okay, got it
Sorry for late response, I have different times
I hope the others could help you
looks structured, or what exactly do you mean?
What I am asking is, if someone sees how my tables are, does it really matter..?
I am assuming it truly does not matter. But I am just wondering if it could lead to a risk some how..?
depends, if it doesn't bother you then I wouldn't worry. But I would still keep something like this safe
Well its only in development, and the only way this user would get their data would be through an email.
I would not share this data through a discord dm. I don't really wanna do that lol
👍
I think the only way they could use the tables is for debugging my bot. But thats just really it. But I doubt even that will do it.
are you sending the whole file through email?
I would probably do that yes.
Its only their data tho
hmm. It doesn't really matter that they can see the table columns since they can't really do much about it either
Worst they could do is copy the tables and use it in their own bot or sum, which idc if they did lol
or use it for debugging my bot, but I don't see how you could use that for debugging
This is all it does right now, yes its in a command, but later on I am going to put it in my api end points for my dashboard so it will be safe. Which will not use a command n stuff like that.
Try sending the data with a different logic, so a nice text with explanation would be good and clear. if you haven't done this yet. so that you don't send everything that is in the data
Well, what I will be doing is, auto emails or something, which will explain everything in the emails. But they will obviously know what it is because they requested the data.
Unless you meant something else..?
If it is their own data then it is not really a problem. Many do not even know what it is exactly. And even if they do, I don’t think they can do anything with it.
👍
That is true. But some like to request their data to see what we keep.
Even tho some don't realize that some companies could just keep data and not even send it.
But I am just auto generating based on their ID, because in all tables anything related to them is related to their ID so I think it should grab everything. If not, we will manually grab it.
👍
Can anyone give me an Example Slash Command for Discord.py?
Slash Command: /test
Description: Test Command
What should it do?
Send the Message: Test worked.
So there are multiple ways. Answer this question for me. Are you wanting to keep prefix commands while having slash commands or only having slash commands?
whats better?
I personally like to keep the prefix, because you can have both and do some other things, but there is no "better" its preference.
Both
Okay.
my prefix is ?
In this situation, the prefix does not matter, and you are not actually gonna change much to make this work actually.
or not
import discord
@bot.hybrid_command()
async def test(ctx):
"""
Test Command
"""
await ctx.send("Test worked.")
You will need to make a sync command.
https://about.abstractumbra.dev/discord.py/2023/01/29/sync-command-example.html
You can understand umbras sync command here, and go off of that, or I can send you a custom one I made, that most people use, so not really custom lol.
I curated and created a pretty full-featured command for syncing your CommandTree, you can see it here:
make sure you have bot n everything else setup n crap. or it won't work. oh and I forgot to mention something hold up.
Are you using cogs..?
no
No
import discord
from discord.ext import commands
from discord import app_commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='?', intents=intents)
@bot.hybrid_command()
async def test(ctx):
"""
Test Command
"""
await ctx.send("Test worked.")
with open('token.txt', 'r') as file:
TOKEN = file.read().strip()
bot.run(TOKEN)```
?
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.reactions = True
super().__init__(command_prefix = "!", intents = intents)
async def setup_hook(self):
await self.tree.sync()
print(f"Synced slash commands for {self.user}.")
async def on_command_error(self, ctx, error):
await ctx.reply(error, ephemeral = True)```
This is just an example. Do not exactly copy this, but you will need to setup something like this at the top of your file because I am assuming most if not all are in 1 file..?
import discord
from discord.ext import commands
from discord import app_commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='?', intents=intents)
@bot.event
async def on_ready():
await bot.tree.sync()
print(f'{bot.user.name} has started and commands are synced.')
@bot.hybrid_command()
async def test(ctx):
"""
Test Command
"""
await ctx.send("Test worked.")
with open('token.txt', 'r') as file:
TOKEN = file.read().strip()
bot.run(TOKEN)
```?
Also, that setup_hook do not copy that for the sync part, you need to setup a custom sync, auto syncing is really bad in your bot, and if you just avoid this in the early stages, you will be clear, which I did not, but I learned later on that it was really bad. So I highly recommend using a custom sysnc command.
Omg finally
No, you need to have that Bot class if you are wanting to learn more "advanced" things, most people have a bot class like that in their bot just for loading cogs n mainly intents.
Also, use setup hook if you are wanting to use auto sync, not on_ready, never pass anything in on_ready unless its something simple like prints or something. on_ready can be triggered many times. and its not stabled. so do not use on_ready for things like that.
A hands-on guide to Discord.py
isn't tree outdated?
never used tree, sorry if that is like a really stupid question lmao
A hands-on guide to Discord.py
have always used hybrid or app_commands
discord.Attachment [AppCommandOptionType.attachment] - An attachment parameter
THATS A THING???
I have it now 🙂
to each his own, everything works great. but this is a good explanation for beginners
Nah I was wondering if it still worked XD
Never tried tree
it works
i have this now:
import discord
from discord.ext import commands
from discord import app_commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='?', intents=intents)
@bot.event
async def on_ready():
await bot.tree.sync()
print(f'{bot.user.name} has started and commands are synced.')
@bot.tree.command(name="help", description="Get Help for bot")
async def help_command(interaction: discord.Interaction):
with open('help_embed.txt', 'r') as file:
help_content = file.read().strip()
embed = discord.Embed(
title="Bot Help",
description=help_content,
color=discord.Color.blue()
)
await interaction.response.send_message(embed=embed)
with open('token.txt', 'r') as file:
TOKEN = file.read().strip()
bot.run(TOKEN)
ah okay then
You can't use prefix commands now for that help command.
But with hybrid, it accepts prefix or slash
thats why I like hybrid lol
But nah I deadass didn't know
discord.Attachment [AppCommandOptionType.attachment] - An attachment parameter
was a thing.. now I can like use this for things.. 😭
Surprised this doesn't show the method to make it using app_commands.
A hands-on guide to Discord.py
app_commands are displayed in cogs 😄
but this is ok for beginners to understand the commands
good night
I wish xD
xD
Trying to finish this Rework for my bot, which we have been working on for awhile, just not enough developers lol
what do you need help with?
We are just currently reworking our entire bot, and we are also making endpoints in our bot for a dashboard, and also slowly reworking our website and some other stuff, we also switched databases
But we are changing everything in the bot, like its a full rework
But there is only 4 devs on this, and mainly only 2-3 are active on it rn
oh
Nah, they volunteer
then i wish you much success!
Ty lol
if I was rich, I would pay them even if they were still volunterr
But I am def not rich 😭
one day..
Maybe 
Thanks for help @vapid parcel!
I tried for 2 Weeks to use Slash Commands and it didnt work, It finally worked because of you:)
Shamir gave you the docs, thank him lol.
#1245671044555997285 send help lol
Guys I'm new to discord py. How can I see the latency of users in a voice chat using discord py?
I came across this implementation, but not quite sure where I can pass the user.
import discord # type: ignore
from discord.ext import commands # type: ignore
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)
@bot.command() # type: ignore
async def check_ping(ctx) -> None:
await ctx.send('Pong! {0}'.format(round(bot.latency, 1)))
bot.run('token')
So, I would like to pass a discord.member.Member which would be a user who is in the voice chat, and have the function return the ping they're getting with respect to the server set in the voice chat.
you can't get the latency of the user
how can i get the img
this is as far as i can get fro arguments
i want a way so i can store the image sent by user
should be in message.attachments
thx
i also have another question i made clean command which make a loop of N and delete messages but i get rate limited
how to fix it so i don't get rate limited
what's your code?
are you doing [x async for x in channel.history(limit=n)] or smth?
no just regular for loop
with asyncio.sleep(1)
and with message.delete() ?
yes
yeah, that's gonna get you rate limited pretty quick, consider purging
so this one is better?
that's not purge
i have trouble understand what is x async
yeah you can bulk delete up to 100 per api call*
i also have another question
i'm trying to print something if discord.NotFound is raised
is this how you invoke it?
where are you doing it
coz i don't know what are those parameters
when i call discord.role.attachement, Im trying to print something if atachement not found
you can access them if you get the error
but this should be correct
thank you
eg.
except discord.NotFound as exc:
print(exc.message)
so to make sure, NotFound is raised not when the atachement is not found, but when its deleted while executing the code right?
coz in the latter, nothing will be raised if you don't provide an atachement in first place
well
if you get an attachment in your message.attachments, it means that it existed when the message was sent, and if it was deleted, then it doesn't exist anymore right
true
icon = ctx.message.attachments
try:
await icon_b = await icon.read()
except discord.NotFound:
print("not found")
await role.edit(display_icon=icon_b)
not sure why this isn't working
await icon_b = ...
oh fuck i'm blind
your editor should yell at you lol
i accidently deleted my nvim config
so i'm literally using nothing but what default nvim offer
even after changing this i don't see anything
any error?
none
wdym loggin?
all other things in the same script work just fine like changing the role name and its color
for getting errors
so issue is in icon.read()
i have the 3 setted up
if i do a general except i get error, but with these specifically i get none
if you mean closing the script yes in the end but its not reaching that end since i'm still in program running
can you send the code where you have the try/except
if "ROLE_ICONS" in ctx.guild.features:
icon = ctx.message.attachments
print(icon)
try:
print("icon read")
icon_b = await icon.read()
print(icon_b)
await bot.close()
except discord.NotFound:
print("not found")
except discord.Forbidden:
print("forbidden")
except discord.HTTPException:
print("http exception")
except:
print("error")
await role.edit(display_icon=icon_b)
there is something i'm unsure about, the except: runs always if there is error regardless if you find it in previous error handlers right? not how if else statement works?
you're suppressing the error in your except:
should be:
except:
raise
``` or just don't have a bare except at all
Yeah, you should remove that except clause and let it go to the error handlers
Oh, i'm so dumb
if you really want one, do something like this
import traceback
#...
except Exception:
traceback.print_exc()
so basically raise it from there and then go to that function, i froget about name of function
@bot.event
async def error_handler()
mine better
idk name exactly but from there i should print something depending on the error raised right?
on_command_error
nw
Yours does literally nothing 💀

@pale zenith help me sir
code py @app_commands.choices(model=[ app_commands.Choice(name="General", value="general"), app_commands.Choice(name="Programación", value="programming") error: Cog error: randomimage: Extension 'src.cogs.randomimage' raised an error: TypeError: unknown parameter given: model
Your async def has no argument model
(either that or you forgot self)
@app_commands.command(name="random-pfp", description="Obten un pfp aleatorio")
@app_commands.choices(model=[
app_commands.Choice(name="General", value="general"),
app_commands.Choice(name="Programación", value="programming")
])
@app_commands.guild_only()
async def random_pfp(self, interaction: discord.Interaction):```
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
click the link and see example 😄
Hey there could somebody help me with something
with?
sorry something is undefined, to fix that define something :)
One message removed from a suspended account.
You're taking more than 3 seconds to respond
One message removed from a suspended account.
That's what that error means
3 seconds or more elapsed between when the interaction was created and when you tried to respond to it
One message removed from a suspended account.
so yall gona answer or
Well one approach would be to profile where the time is being spent rather than looking at the code and guessing
You also shouldn't be using a flat json file as a db if that's what you're doing
One message removed from a suspended account.
Either look up some profiling frameworks, or hell just add print statements with the current time in some places
asyncio debug mode is also a good option to see if you have code that is blocking
One message removed from a suspended account.
One message removed from a suspended account.
If you run that within 3 seconds of the interaction happening, sure
One message removed from a suspended account.
One message removed from a suspended account.
When the user performs the interaction in discord yeah
One message removed from a suspended account.
how so i like make this hybrid command work? It just says application not responding ? https://sourceb.in/E4ijUDsJBm
hi, i recently start developing an image generation discord bot using js and py
from diffusers import DiffusionPipeline
def generate_image(prompt):
pipeline = DiffusionPipeline.from_pretrained("UnfilteredAI/NSFW-gen-v2")
image = pipeline(prompt).images[0]
image_path = "generated_image.png"
image.save(image_path)
return image_path
if __name__ == "__main__":
import sys
prompt = sys.argv[1]
image_path = generate_image(prompt)
print(image_path)```
it works great, the only problem is it is so painfully slow taking about 30 mins per image
how can i make this faster
Set it to use the GPU if you have one. Also code itself isn't Discord bots related
Better ask somewhere else like: #1035199133436354600
how can i set it to do so
pipeline = pipeline.to("cuda")
There are also more things you can do to speed it up, take a look at: https://huggingface.co/docs/diffusers/tutorials/fast_diffusion
thank you!
can i dm you
No
File "C:\Users\ultra\Desktop\dwe\s.py", line 2, in <module>
from diffusers import DiffusionPipeline
File "C:\Users\ultra\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\diffusers\__init__.py", line 5, in <module>
from .utils import (
File "C:\Users\ultra\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\diffusers\utils\__init__.py", line 97, in <module>
from .peft_utils import (
File "C:\Users\ultra\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\diffusers\utils\peft_utils.py", line 28, in <module>
import torch
File "C:\Users\ultra\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\torch\__init__.py", line 141, in <module>
raise err
OSError: [WinError 126] The specified module could not be found. Error loading "C:\Users\ultra\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\torch\lib\shm.dll" or one of its dependencies.```
this is the error im getting do i need to enable something on my gpu
OOO error debugging! Lesseeeee
🤔
I got nothing. Did you try installing everything?
@Client.command(description="`adds a role to all users.`") async def addroleall(ctx, role: discord.Role, user: discord.Member): if ctx.author.guild_permissions.administrator: m = await ctx.send('Adding roles...') await m.add_reaction(':white_check_mark:') await user.add_roles(role)
I want to make a command that adds roles to everyone
Just dont know where im wrong
Hi
Remove user: discord.Member
Add
for users in ctx.guild.members:
await users.add_role(role)
…
Hello can anyone use @tasks.loop() with 'time' parameter? I copied an example code from documentation and it doesn't work. Does bot needs some very specific intents to run @task.loop() with 'time' parameter?
`import datetime
from discord.ext import commands, tasks
from config import TEST_SERVER
utc = datetime.timezone.utc
If no tzinfo is given then UTC is assumed.
time = datetime.time(hour=9, minute=23, tzinfo=utc)
class MyCog(commands.Cog):
def init(self, bot):
self.bot = bot
self.my_task.start()
def cog_unload(self):
self.my_task.cancel()
@tasks.loop(time=time)
async def my_task(self):
print("My task is running!")
@commands.command()
async def test_ping(self, ctx):
await ctx.send("Test ping")
async def setup(bot:commands.Bot) -> None:
await bot.add_cog(MyCog(bot), guild=TEST_SERVER) `
i only added setup and test ping command which works, and ofcourse change time parameters.
No intents are for discord events
Code looks fine to me
Could you try it without specifying the tzinfo
If you haven't fixed it already
Would you have me an plan to start python
it doesn't want to cooperate anyway :/
anyone mind helping
https://paste.pythondiscord.com/CEVQ
2024-05-31 14:30:54 ERROR discord.app_commands.tree Ignoring exception in command 'giveaway'
Traceback (most recent call last):
File "/home/runner/Run-bot/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "/home/runner/Run-bot/main.py", line 606, in start_giveaway
duration_seconds, duration_text = parse_duration(duration)
TypeError: cannot unpack non-iterable datetime.timedelta object
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Run-bot/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/Run-bot/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/Run-bot/.pythonlibs/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'giveaway' raised an exception: TypeError: cannot unpack non-iterable datetime.timedelta object
One message removed from a suspended account.
One message removed from a suspended account.
alr
nah it didnt work
One message removed from a suspended account.
are you from qatar?
oh, cool
when a user clicks a button how can i make it check if that user is in a sepearate server
```@Client.command(description="Send some feedback about Duke.")
async def feedback(ctx, *,message):
emb=discord.Embed(title=f"Feedback from: {ctx.author}", description=f'{message}', color=discord.Color.blue())
emb.set_footer(text=f"Sent by - {ctx.author}", icon_url=ctx.author.avatar_url)
feedbk_chan = Client.get_channel(1244959858998902804)
message = await feedbk_chan.send(embed=emb)```
AttributeError: 'Member' object has no attribute 'avatar_url'
my error could someone explain what i have to replace exactly
its icon_url=author.display_avatar.url
send the error then
ok
this one?
yes
one sec
:incoming_envelope: :ok_hand: applied timeout to @true jay until <t:1717181018:f> (10 minutes) (reason: duplicates spam - sent 6 duplicate messages).
The <@&831776746206265384> have been alerted for review.
such eccentric shit happens in here 😭
can anyone help me here https://discord.com/channels/267624335836053506/1246179295483793444
it's almost half an hour I am asking here because after 1 hr it closes
wth does this actually mean im confused (using nextcord)
i have self in the parameters
https://github.com/nextcord/nextcord/blob/v2.6.1/nextcord/application_command.py#L791-L796
according to source code, that warning only appears if you don't have two non-optional parameters, so presumably that means your second parameter has an unnecessary default? nvm it really does mean what it says, you're probably missing interaction
nextcord/application_command.py lines 791 to 796
if self.parent_cog is not None and non_option_params < 2:
warnings.warn(
f"Callback {self.error_name} is missing the self and/or interaction parameters. Please double check your function definition.",
stacklevel=0,
category=MissingApplicationCommandParametersWarning,
)```
the signature should look something like this, with no defaults for self or interaction
https://github.com/nextcord/nextcord/blob/v2.6.1/examples/application_commands/cog_example.py#L12
examples/application_commands/cog_example.py line 12
async def my_slash_command(self, interaction: nextcord.Interaction):```
oh wait a minute, non_option_params is not what i thought it meant
is it choices
i think so, just above that snippet it's trying to count parameters with Self/Interaction annotations (or no annotation) to infer whether they're present
heh, nextcord has 21 warnings.warn() calls compared to 3 in discord.py's source
26 to 21 with _log.warning() too
Hi. So I'm trying to have one part of my command add a role, then if they have another role (some will and some won't) remove that role. This is what I did. However, it adds the role correctly but does not remove the role.
removerole = guild.get_role(cfg.removerole_id)
if role in user.roles: return
if percent >= cfg.min_percent and counted >= cfg.min_counts and saves >= cfg.min_saves:
await user.add_roles(role)
await user.remove_roles(removerole)```
ratelimit maybe? not sure what the typical ratelimit for that endpoint is
looks like its 10/10s for me, and add/remove share the same bucket, so that probably isn't it...
if removerole and removerole in user.roles:
await user.remove_roles(removerole)
try it with that, should actually work
Thank you that worked and doesn't throw and error if they don't have the role 🙂 I just moved it to the end of the section so it did the rest of the commands that came after that snippet even if they did have a role.
This shouldn't work
hi
yes
@slate swift
Dm
client = commands.Bot(command_prefix = 'd!', intents = discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)```
ModuleNotFoundError: No module named 'discord_slash'```
what exactly do i do to fix this?
install discord_slash
its replit.
Anyone?
youwork with the apollo bot?
Beta Tester of it, yes
pip install discord_slash
are you trying to add a button to the view?
yeah
many buttons with the number of cogs
you need to use the @discord.ui.button() decorator
how do I add in loop then
ok what you want is to creat a button class that you can add multiple times then
button callbacks don't take a button arg
oh
some do
Okay but how do I disable the button if I dont pass it
only if made via decorator
ye
either subclass ui.Button and add it or use the decorator
button.view
Oh alr
!d discord.ui.Button.callback
ok so to create a button class, simply do ```py
class MyButton(Button):
def __init__(self, label, style, emoji, custom_id, row):
super().__init__(label=label, style=style, custom_id=custom_id, emoji=emoji, row=row)
async def callback(self, interaction):
pass # button callback stuff```
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
wait....they do
depends how you create the button
yeah
only if created by decorator
Yeah
if you subclass the button like this @copper flume , you can access the parent view with self.view
haven't seen many people use the subclassing method to create buttons sooooo
Yeah I did it.
let me test it
OOP hehe
Yeah because it makes it more complicated and long lines of code
if you do OOP it lets you do more things
and considering the fact that many people who come here don't even try to learn python properly 😭you're quite right
👌
did it work?
I would make it a dropdown menu
since there is a limit on buttons
you are restricted to 5x5 grid so if you add more cogs you might run out of space
i have select menu currently for a long time
and now I wanna make something cool
i mean.. don't fix it if it ain't broke 😉
oop wait i forgot to mention what im facing
so im using that code to paginate a list called glist and the first page is completely fine buttt, when i switch to any page except the first one it displays the information which was present on page 1 instead of continuing the data from where it was left on previous page and this happens on every page
consider changing```py
current_page : int = 1
sep : int = 5
to
```py
def __init__(self, *args):
self.current_page: int = 1
self.sep: int = 5```
otherwise I don't think self.current_page is defined
alright i did it and it works, thanks
😔
guys is it possible to make it so every command can only be ran by people with a specific role from just only editing the main.py file and not every single cog?
u can manually iterate over each command and then use add_check i think
tried doing that and it didnt work anyways so i'll just add the check to each command separately
will take less time than me figuring this out
you can use the on_command event and check if the author/user has the specific role or not
i've already started to change the cogs manually so
tf
uhhh alright
python is tripping yr
real
it would hve been easier to use the event
!d discord.discord.ext.commands.on_command
discord.ext.commands.on_command(ctx)```
An event that is called when a command is found and is about to be invoked.
This event is called regardless of whether the command itself succeeds via error or completes.
im using nextcord though remember
it's the same
oh
it's a 🍴
trident and butter knife
spork
uhm, ig should be possible
discord has a built in feature for that for server admins i think
where are you defining it?
is your function get_prefix or is get_prefix a variable
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
@client.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = '?'
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@client.event
async def on_guild_remove(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes.pop(str(guild.id))
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
@client.command()
async def changeprefix(ctx, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'**Prefix changed to {prefix}**')```
heres the code
change it to have a () on get_prefix
kk
no, you dont have a message to pass
oh yeah that too
nope.

