#discord-bots

1 messages · Page 369 of 1

young dagger
#

Thanks

shrewd vapor
#

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

fast osprey
#

You have blocking code somewhere most likely

shrewd vapor
#

My code was working fine 3 days ago

#

i have this problem since yesterday

twilit grotto
shrewd vapor
#

no

quick gust
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

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!
shrewd vapor
#

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 ?

quick gust
#

you use the requests library?

shrewd vapor
#

yes

quick gust
#

yeah then use aiohttp

#

requests is probably causing that error

shrewd vapor
#

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)```
quick gust
#

youll only have the modify the code slightly to use aiohttp

shrewd vapor
#

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 ?
quick gust
#

try it

shrewd vapor
#

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

slim bloom
#

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)]

upbeat otter
slim bloom
upbeat otter
#

I see

upbeat otter
slate swan
#

I mean, the error pretty much says it all.. It's unreachable

limber jolt
#

How would I ping a user?

#

Not an embed.

quick gust
#

!d discord.User.mention

unkempt canyonBOT
limber jolt
slate swan
quick mist
#

!e s

unkempt canyonBOT
# quick mist !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
quick mist
#

!e
import requests

unkempt canyonBOT
# quick mist !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'
quick mist
#

!e
import urllib3, urllib

unkempt canyonBOT
# quick mist !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'
quick mist
#

!e
import urllib2

unkempt canyonBOT
# quick mist !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'
quick mist
#

!e
import os

unkempt canyonBOT
quick mist
#

!e
import subprocess

unkempt canyonBOT
quick mist
#

!e
import subprocess
print(subprocess.check_output("apt -v").decode())

unkempt canyonBOT
# quick mist !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

quick mist
#

!e
import subprocess
print(subprocess.check_output("apt -v", shell=True).decode())

unkempt canyonBOT
# quick mist !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

quick mist
unkempt canyonBOT
quick mist
#

!e
print(import("subprocess").check_output("curl"))

unkempt canyonBOT
# quick mist !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

quick mist
#

!e
print(import("subprocess").check_output("curl",shell=True))

unkempt canyonBOT
# quick mist !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

quick mist
#

!e
print(import("os").system("whoami && id"))

unkempt canyonBOT
quick mist
#

!e
from threading import Thread
def wait():

import("time").sleep(100)

for _ in range(5000): Thread(target=main).start()

unkempt canyonBOT
quick mist
#

!e
from threading import Thread
def wait():

import("time").sleep(100)

for _ in range(5000): Thread(target=wait).start()

unkempt canyonBOT
# quick mist !e from threading import Thread def wait(): __import__("time").sleep(100) fo...

: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
quick mist
#

!e
def wait():

import("time").sleep(100)

for _ in range(5000): import("threading").Thread(target=wait).start()

unkempt canyonBOT
# quick mist !e def wait(): __import__("time").sleep(100) for _ in range(5000): __import_...

: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
quick mist
#

!e
def wait():

import("time").sleep(100)

for _ in range(50000): import("threading").Thread(target=wait).start()

unkempt canyonBOT
# quick mist !e def wait(): __import__("time").sleep(100) for _ in range(50000): __import...

: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
fast osprey
#

You good?

timber dragon
#

I don't think so

#

#bot-commands exists btw

hollow hemlock
#

how would I see who the user pinged from a slash command?

@client.hybrid_command()
async def requesthelp(ctx: commands.Context, user: str):
quick mist
young dagger
#

Channel sidebar is to the left, members list to the right. What is the middle part called?

glad cradle
#

that's a forum channel

young dagger
glad cradle
#

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

woven sparrow
#

Can someone help me with my bot command? HMU

chilly cloud
#

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

fast osprey
#

replit is not made for running bots. It was designed for hosting web code. It is extremely unfit for purpose, especially at that price

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

blissful crane
slate swan
#

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.

quick mist
slate swan
quick mist
#

Did you make the script? Or are you using the Repl.it's discordpy template?

shadow vigil
timber dragon
#

Or use both

limber jolt
#

!e

unkempt canyonBOT
#
Missing required argument

code

limber jolt
unkempt canyonBOT
# limber jolt !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.

languid jungle
#

!unmute 1228732555591684208

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction timeout for @limber jolt.

languid jungle
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the 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.

languid jungle
#

Use our pastebin

limber jolt
limber jolt
languid jungle
chilly cloud
fast osprey
#

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

chilly cloud
fast osprey
#

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.

wheat adder
void basin
chilly cloud
upbeat otter
#

.

void basin
#

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

wispy falcon
#

Why does this not work?
it doesnt even print any error or something and my bot has the permissions

upbeat otter
#

doesn't exist

hushed galleon
#

only on_guild_channel_create is a valid event so you'll need to check the channel's type there

wispy falcon
chilly cloud
fast osprey
#

If a vps doesn't just give you ssh access to do whatever you want, it's a scam

chilly cloud
#

I wonder what this does lmfao

patent hull
#

:fall:

#

would probably be banned of discord API temporarily

fast osprey
#

Even for stupid skid meme code this is just dumb

patent hull
#

fr

upbeat otter
#

who even tries to nuke a server anymore

patent hull
#

lol

fast osprey
#

Plenty of shitty little kids with nothing better to do

upbeat otter
#

fr

chilly cloud
void basin
crimson charm
#

Does anyone know why this happens?

timber dragon
shrewd apex
#

npm install failed

upbeat otter
#

you'll get blocked

chilly cloud
fast osprey
#

It doesn't even work in all cases

#

For being so "easy" skids still screw things up

chilly cloud
slim bloom
#

How do I set cooldowns to slash app commands?

fast osprey
#

!d discord.app_commands.checks.cooldown

unkempt canyonBOT
#

@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:
slim bloom
#

thx

slate swan
glad cradle
#

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

slate swan
#

you can use a premade image with heart and add avatars to it.

#

it nottttt

glad cradle
slate swan
#

ohhhhh

slate swan
#

mb ty

#

and if u want nitro just pretend to be a girl and use :3 and ;3 and make your words looonger 💀

glad cradle
#

UwU, ty! ;3

finite salmon
slim bloom
# fast osprey !d discord.app_commands.checks.cooldown
@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

shrewd apex
#

set an else statement for ur error handler to see if its being eaten up

slim bloom
#

:v

unkempt cloud
#

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?

shrewd apex
unkempt cloud
# shrewd apex what does ur bot do?

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.

slim bloom
#

The mistake was that I forgot about self as the first argument of the error

shrewd apex
#

ic glad we caught it

slim bloom
primal sail
#

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:

harsh galleon
#

Anybody know how to fix this error?

slim bloom
#

I have to add else: raise error in all the commands of my bot? and there is no system or something that is global?

slim bloom
#

in your host

harsh galleon
vapid parcel
vapid parcel
#

nvm I fixed the issue... un optimized code. Went from 3 seconds to less than a second.

abstract lance
#

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

abstract lance
#

Yeah, thanks, figured the issue out. I was using a link button but in reality I just wanted a grey one

vapid parcel
#
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?

upbeat otter
vapid parcel
#

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

vapid parcel
upbeat otter
#

for example, if you're logging in a discord channel, use webhooks

vapid parcel
#

/v10/channels/1156177041528463432/webhooks

upbeat otter
vapid parcel
#

theres over this many people 150,504

#

But imma just uh

#

yea

blazing condor
#

are there any loops/repeated actions that could be causing this?

#

would be my guess.

#

@vapid parcel

vapid parcel
#

it would be happening in other servers too

#

Not only 1

blazing condor
#

fair point.

vapid parcel
#

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!

versed basalt
#

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

naive briar
#

!d discord.app_commands.command

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
versed basalt
shrewd apex
#

once all cogs are loaded

versed basalt
#

awesome, thanks for the assistance

slate swan
#

@unkempt canyon

upbeat otter
storm leaf
#

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?

pale zenith
#

(that is to enable the "add app" button in the user profile. For who? nobody can add it)

storm leaf
#

If I want to keep it private, how do I go about that

pale zenith
#

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?

storm leaf
#

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 😂

pale zenith
#

Show please (a screenshot) (im confused)

storm leaf
#

YOu mean this right?

#

OAuth -> Redirects

pale zenith
#

What happens when you set it to private?

storm leaf
pale zenith
#

Try going to installation and disabling that shit

#

Install link [...] None

#

Just tested it, should work

storm leaf
#

Okay

#

So setting link to none fixes it, was that the "add app" link?

pale zenith
#

Yeah

storm leaf
#

Aah you're a legend

pale zenith
storm leaf
#

Tyvm, fuck sake

pale zenith
#

stupid ass way to do that BUT OK DISCORD

storm leaf
#

Yeah it's very annoying, tyvm sir

pale zenith
#

np

storm leaf
#

saved me a couple of hours 😂

storm leaf
# pale zenith np

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?

pale zenith
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

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

This must be called for the application commands to show up.
storm leaf
#

Is there a "fuller" example of this?

#

Yeah I'm doing something wrong, but I'll look into it, thanks! 😄

storm leaf
storm leaf
#

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 😂

pale zenith
#

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

storm leaf
#

Can I just make another slash command to sync my new commands?

#

Or did I misunderstand you

pale zenith
pale zenith
#

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

storm leaf
pale zenith
#

yea but that sounds annoying

subtle ingot
#

where do you guys host the bots? i made a code but there’s a lot of options im looking at

fast osprey
#

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
wanton current
#

ah yes

#

my favourite host

quartz ibex
#

Fr

subtle ingot
slate swift
#

why am i getting an error??

#

still not working

#

its already satisfied

#

@arctic zodiac

wanton current
#

tf is pytoileur

slate swift
wanton current
#

yeah, definitely don't install that

#

there are some typos in your code that probably causes the error

slate swift
glacial sail
#

!cban 1213823510439264297 spreading malware

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @arctic zodiac permanently.

slate swift
glacial sail
#

you probably already have been

slate swift
#

shouldn't it be blacklisted or something.

glacial sail
#

malware gets blacklisted once someone notices it

slate swift
#

ban also didn't work on him

glacial sail
#

this one wasn't noticed yet, it seems

wanton current
slate swift
glacial sail
obtuse lark
#

Aoba seus gringos

glacial sail
#

from a different device

obtuse lark
#

Sou brasileiro seloko

glacial sail
#

^ @slate swift

slate swift
glacial sail
slate swift
#

i thought he was legit because i didnt know there was malware in the pips that people could make :/

glacial sail
#

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

glacial sail
#

when you installed the malware, it should have created that executable and that directory

slate swift
#

do i open the the command prompt or what

glacial sail
#

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?

glacial sail
#

yeah, so it very likely infected you successfully, then

slate swift
#

Please someone help me

winged forge
#

u need to use intesnt

#
intents = discord.Intents.default()```
merry cliff
slate swift
#

@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")```
merry cliff
#

!traceback

unkempt canyonBOT
#
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.

slate swift
merry cliff
#

Oh

winged forge
#

pip install discord

merry cliff
#

Yeah run that in the terminal

#

Not as python code

winged forge
slate swift
#

i already did thats the thing

winged forge
merry cliff
#

Do you have multiple python versions?

winged forge
#

dont forget .py

slate swift
winged forge
slate swift
merry cliff
merry cliff
slate swift
merry cliff
#

Curious

#

Did you install from website or ms store

slate swift
#

i deleted it from my settings

#

and redownloaded from website

winged forge
merry cliff
#

!pypi discord

unkempt canyonBOT
merry cliff
#

It’s literally a mirror package

winged forge
#

for check if u downlaod 'pip' or no

merry cliff
#

????

slate swift
#

@merry cliff what should i do?

merry cliff
#

Try py -m pip install -U discord

merry cliff
slate swift
dapper sluice
#

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

slate swift
#

ITS FUXED

merry cliff
#

No problem

slate swift
dapper sluice
#

just self use ye

#

are u sending an embed

#

think descriptions are only for embeds?

merry cliff
#

Yeah

glacial sail
#

You spelled "description" wrong

slate swift
#

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

slim bloom
#

Should I put else: raise error in all my bot commands? Is it advisable?

hollow parrot
vapid parcel
#

Which is more common?

DD/MM/YYYY?

or

MM/DD/YYYY

slim bloom
vapid parcel
#

Everyone else uses DD/MM/YYYY i think..?

hushed galleon
hushed galleon
#

but you can be grateful that you don't need to guess the format between DD/MM/YYYY or MM/DD/YYYY 🥴

vapid parcel
#

I will just use DD/MM/YYYY

#

if someone wants to complain, then thats on them shrug

#

Im used to MM/DD/YYYY but I know majority of the world uses DD/MM/YYYY so I am going to use that...

hushed galleon
#

as long as its in your prompt, it shouldnt be too confusing

#

date picker component when pithink

#

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

karmic oriole
#

how do i change the displayname of my discordbot in the server

hushed galleon
#

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()

vapid parcel
#

How could I make this better? This is sent to the users dms.

hushed galleon
#

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

vapid parcel
#

Because I have no clue on how I wanna do all of that 😭

#

I could use pytz or whatever its called

hushed galleon
#

(but on windows you need tzdata installed for it to work correctly)

vapid parcel
#

so don't use pytz..?

hushed galleon
#

if you have 3.9+, use zoneinfo instead

vapid parcel
#

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

main holly
#

whats the best code for making slash commands

hushed galleon
main holly
#

bot.tree.command? or something else

vapid parcel
#

they can delete it, then remake their stuff

hushed galleon
vapid parcel
hushed galleon
#

though afaik discord.py's still the most popular from the rest, so you're probably most likely to get support for it here

vapid parcel
main holly
#

i know, i have code for buttons

hushed galleon
#

message components are implemented almost the same between dpy and its forks

vapid parcel
#

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?

hushed galleon
vapid parcel
hushed galleon
vapid parcel
#

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

stray flax
#

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.

shrewd apex
#

print out the data once to see if it is what ur expecting

vapid parcel
#

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.

shrewd apex
#

supabase ducky_beer

vapid parcel
#

I have no clue what else to add to the birthdays tho, if anyone has ideas, lmk!

shrewd apex
#

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

shrewd apex
#

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

vapid parcel
#

Oh so like

#

Okay so I understand what u mean

#

But images would be hard to store.

shrewd apex
#

supabase has a blob store

vapid parcel
#

For images?

shrewd apex
#

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

vapid parcel
shrewd apex
#

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

vapid parcel
#

they updated that bro bro 😭

shrewd apex
#

ah

vapid parcel
#

Unless im behind..?

shrewd apex
#

haven't messed with attachments in a long time

quick gust
shrewd apex
#

prolly some cdn stuff

vapid parcel
#

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.

quick gust
#

ah i see

vapid parcel
#

But don't quote me on that, I could be completely wrong.

shrewd apex
#

so it should work right

#

try it lol

vapid parcel
#

cuz when I resend that link, that link will be expired, but the ones inside of discord, were edited I think..?

shrewd apex
#

they prolly check for incoming host request to their cdn

#

if its present in a whitelist

vapid parcel
#

Idk how it really works, its really wonky

shrewd apex
#

they maintain

vapid parcel
#

its fucking weird tho. Its smart how they do it tho

#

cuz they are saving HELLA money rn

shrewd apex
#

no idea lol i gotta look into it

shrewd apex
#

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

vapid parcel
#

Someone gave me these ideas

#

which are cool ideas

shrewd apex
#

thats cool too

vapid parcel
#

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

vapid parcel
drifting arrow
#

Hey, what's the decorator to make a slash command admin only?

quick gust
fast osprey
unkempt canyonBOT
#

@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.
vapid parcel
#

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

civic reef
#

How to add this changing bio to discord bot?

#

I wanna add QBit there

#

so it will be visible at first glance

ancient stump
civic reef
#

yeah

#

or only QBit

naive briar
unkempt canyonBOT
#

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...
civic reef
#

okay

ancient stump
# civic reef okay

await bot.change_presence(activity=discord.CustomActivity(name='QBit'))

would also be a solution for your wish

fast osprey
#

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

limber jolt
#

I know more about bots than basic Python

ancient stump
limber jolt
spice warren
#

Congrats, that means you know Python

#

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

slate swan
versed basalt
#
@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

spice warren
#

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

versed basalt
#

lol

ancient stump
versed basalt
#

just have gpt do everything for you. Cant fail

glad cradle
#

😐

vapid parcel
vapid parcel
unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

versed basalt
#

i was only joking, i'm sorry

ancient stump
vapid parcel
#

Oh ok

vapid parcel
timber dragon
#

Good music.

ancient stump
ancient stump
karmic oriole
#

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

twilit grotto
karmic oriole
vapid parcel
#

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.

slate swan
#

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.

vapid parcel
#

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

quick gust
#

Just fetch all the data you're storing from the database related to the user?

drifting arrow
#

soo.. how we all doing today?

slate swan
#

Better

#

How is you?

civic reef
drifting arrow
#

Better than what?

drifting arrow
civic reef
#

I am facing difficulty

slate swan
#

Earlier

civic reef
#

in events.py

quasi bough
#

!d discord.Client

unkempt canyonBOT
#

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

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

New in version 2.0.

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

ok, what does it mean?

upbeat otter
# civic reef 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())```
vapid parcel
#

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:

ancient stump
#

I hope the others could help you

ancient stump
vapid parcel
#

I am assuming it truly does not matter. But I am just wondering if it could lead to a risk some how..?

ancient stump
vapid parcel
#

I would not share this data through a discord dm. I don't really wanna do that lol

ancient stump
#

👍

vapid parcel
#

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.

upbeat otter
vapid parcel
#

Its only their data tho

upbeat otter
vapid parcel
#

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.

ancient stump
# vapid parcel I would probably do that yes.

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

vapid parcel
#

Unless you meant something else..?

ancient stump
#

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.

vapid parcel
#

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.

south narwhal
#

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.

vapid parcel
south narwhal
#

whats better?

vapid parcel
#

I personally like to keep the prefix, because you can have both and do some other things, but there is no "better" its preference.

south narwhal
#

Both

vapid parcel
#

Okay.

south narwhal
#

my prefix is ?

vapid parcel
#

In this situation, the prefix does not matter, and you are not actually gonna change much to make this work actually.

south narwhal
#

ok

#

can you dm me the example?

vapid parcel
#
import discord


@bot.hybrid_command()
async def test(ctx):
    """
    Test Command
    """
    await ctx.send("Test worked.")
south narwhal
#

when the bot restart it will be refreshed

#

?

vapid parcel
#

You will need to make a sync command.

vapid parcel
#

Are you using cogs..?

south narwhal
#

no

vapid parcel
#

Okay

#

do you have a class Bot setup?

south narwhal
#

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)```
?
vapid parcel
#
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..?
south narwhal
#

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)
```?
vapid parcel
#

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.

south narwhal
#

Omg finally

vapid parcel
#

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.

vapid parcel
#

isn't tree outdated?

#

never used tree, sorry if that is like a really stupid question lmao

vapid parcel
#

have always used hybrid or app_commands

#

discord.Attachment [AppCommandOptionType.attachment] - An attachment parameter

THATS A THING???

south narwhal
#

I have it now 🙂

ancient stump
vapid parcel
#

Never tried tree

ancient stump
south narwhal
#

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)
vapid parcel
#

ah okay then

vapid parcel
#

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

vapid parcel
ancient stump
#

app_commands are displayed in cogs 😄

#

but this is ok for beginners to understand the commands

vapid parcel
#

I didn't see that option when reading lol

#

plus its 4am

ancient stump
vapid parcel
#

I wish xD

ancient stump
#

xD

vapid parcel
#

Trying to finish this Rework for my bot, which we have been working on for awhile, just not enough developers lol

ancient stump
#

what do you need help with?

vapid parcel
#

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

ancient stump
#

oh

vapid parcel
#

yeah

#

its a lot of work xD

ancient stump
#

yep

#

are the devs actually paid for this?

vapid parcel
#

Nah, they volunteer

ancient stump
vapid parcel
#

Ty lol

#

if I was rich, I would pay them even if they were still volunterr

#

But I am def not rich 😭

vapid parcel
#

Maybe shrug

south narwhal
#

Thanks for help @vapid parcel!

#

I tried for 2 Weeks to use Slash Commands and it didnt work, It finally worked because of you:)

vapid parcel
#

Shamir gave you the docs, thank him lol.

south narwhal
chilly cloud
ancient stump
#

Tic Tac Toe on discord

#

does anyone have any suggestions or improvements?

upbeat pewter
#

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.

upbeat otter
slate swan
#

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

wanton current
#

should be in message.attachments

slate swan
#

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

wanton current
#

what's your code?

#

are you doing [x async for x in channel.history(limit=n)] or smth?

slate swan
#

with asyncio.sleep(1)

wanton current
#

and with message.delete() ?

slate swan
#

yes

wanton current
#

yeah, that's gonna get you rate limited pretty quick, consider purging

wanton current
#

that's not purge

slate swan
#

i have trouble understand what is x async

slate swan
#

oh so i should perge them instead of deleting them

#

purrge*

#

purge*

wanton current
#

yeah you can bulk delete up to 100 per api call*

slate swan
#

i also have another question

#

i'm trying to print something if discord.NotFound is raised

slate swan
wanton current
#

where are you doing it

slate swan
#

coz i don't know what are those parameters

slate swan
wanton current
#

but this should be correct

slate swan
slate swan
wanton current
slate swan
#

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

wanton current
#

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

slate swan
#

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

wanton current
#

await icon_b = ...

slate swan
#

oh fuck i'm blind

wanton current
#

your editor should yell at you lol

slate swan
#

i accidently deleted my nvim config

#

so i'm literally using nothing but what default nvim offer

slate swan
wanton current
#

any error?

slate swan
#

none

wanton current
#

hmm

#

do u have logging set up?

slate swan
#

wdym loggin?

#

all other things in the same script work just fine like changing the role name and its color

wanton current
slate swan
#

so issue is in icon.read()

slate swan
#

if i do a general except i get error, but with these specifically i get none

wanton current
#

are you suppressing the errors perhaps?

#

code?

slate swan
#

if you mean closing the script yes in the end but its not reaching that end since i'm still in program running

wanton current
#

can you send the code where you have the try/except

slate swan
#
        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?

wanton current
#

you're suppressing the error in your except:

#

should be:

except:
    raise
``` or just don't have a bare except at all
pale zenith
#

Yeah, you should remove that except clause and let it go to the error handlers

pale zenith
#

if you really want one, do something like this

import traceback
#...
except Exception:
    traceback.print_exc()
slate swan
#

so basically raise it from there and then go to that function, i froget about name of function

#

@bot.event
async def error_handler()

slate swan
wanton current
#

on_command_error

slate swan
#

yes1

#

its working now thanks to yall

wanton current
#

nw

pale zenith
wanton current
slim bloom
#

@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

pale zenith
#

(either that or you forgot self)

slim bloom
# pale zenith (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):```
pale zenith
unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
pale zenith
#

click the link and see example 😄

shy eagle
#

Hey there could somebody help me with something

ancient stump
shadow vigil
slate swan
#

Is this title or author field

#

also whats that to the top of it

slate swan
#

One message removed from a suspended account.

fast osprey
#

You're taking more than 3 seconds to respond

slate swan
fast osprey
#

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

slate swan
slate swan
fast osprey
#

You also shouldn't be using a flat json file as a db if that's what you're doing

slate swan
fast osprey
#

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

slate swan
#

One message removed from a suspended account.

fast osprey
#

If you run that within 3 seconds of the interaction happening, sure

slate swan
#

One message removed from a suspended account.

fast osprey
#

When the user performs the interaction in discord yeah

slate swan
slate swan
slate swan
#

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
naive briar
#

Set it to use the GPU if you have one. Also code itself isn't Discord bots related

naive briar
slate swan
#

thank you!

naive briar
#

No

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

drifting arrow
#

OOO error debugging! Lesseeeee

#

🤔

#

I got nothing. Did you try installing everything?

shy eagle
# ancient stump with?

@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

vapid patrol
#

Hi

ancient stump
#

Add


for users in ctx.guild.members:
        await users.add_role(role)
…
shy eagle
#

Alright thanks

#

Btw do you know any good bot hosting sites to use?

azure glacier
#

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.

timber dragon
#

Could you try it without specifying the tzinfo
If you haven't fixed it already

rare mesa
#

Would you have me an plan to start python

azure glacier
clever spade
#

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

slate swan
#

One message removed from a suspended account.

clever spade
#

alr

clever spade
slate swan
ancient stump
clever spade
#

well no

#

but lived here for 12 yrs

ancient stump
#

oh, cool

left dew
#

when a user clicks a button how can i make it check if that user is in a sepearate server

shy eagle
#

```@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

left dew
shy eagle
#

thanks

#

nvm @left dew still not working

left dew
#

what error

#

mb its icon_url=ctx.author.display_avatar.url

shy eagle
#

hopefully

#

yeah same error

left dew
#

send the error then

shy eagle
#

ok

shy eagle
#

yes

left dew
#

works for me

#

do u have members intent enabled?

shy eagle
#

uh

#

one min

left dew
shy eagle
#

one sec

unkempt canyonBOT
#

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

upbeat otter
#

such eccentric shit happens in here 😭

civic reef
#

it's almost half an hour I am asking here because after 1 hr it closes

upbeat mason
#

wth does this actually mean im confused (using nextcord)

#

i have self in the parameters

hushed galleon
unkempt canyonBOT
#

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,
    )```
hushed galleon
unkempt canyonBOT
#

examples/application_commands/cog_example.py line 12

async def my_slash_command(self, interaction: nextcord.Interaction):```
hushed galleon
#

oh wait a minute, non_option_params is not what i thought it meant

wanton current
#

is it choices

hushed galleon
#

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

simple gulch
#

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)```
hushed galleon
#

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

ancient stump
simple gulch
visual crypt
#

Hello?

#

Anyone here

slate swift
visual crypt
#

Yo

#

@slate swift
You make bots

slate swift
visual crypt
#

@slate swift
Dm

shy eagle
#

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?

copper flume
#

install discord_slash

shy eagle
#

its replit.

copper flume
#

use shell

#

or go to packages and install

shy eagle
#

oh shoot i forgot that existed😆

#

alright thanks

copper flume
#

Anyone?

shy eagle
#

youwork with the apollo bot?

copper flume
#

Beta Tester of it, yes

shy eagle
#

thats cool

#

btw whats the command to install the slash commands?

copper flume
#

pip install discord_slash

shy eagle
#

ERROR: No matching distribution found for discord_slash

#

oh god

merry cliff
#

are you trying to add a button to the view?

copper flume
#

many buttons with the number of cogs

merry cliff
#

you need to use the @discord.ui.button() decorator

copper flume
merry cliff
#

ok what you want is to creat a button class that you can add multiple times then

patent hull
#

button callbacks don't take a button arg

merry cliff
copper flume
patent hull
merry cliff
#

ye

patent hull
copper flume
#

Okay.

#

if I subclass it how will I get view.children

#

I need to pass it?

patent hull
#

button.view

copper flume
#

Oh alr

patent hull
#

!d discord.ui.Button.callback

merry cliff
#

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```
unkempt canyonBOT
#

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.
upbeat otter
merry cliff
upbeat otter
#

yeah

patent hull
copper flume
merry cliff
upbeat otter
#

haven't seen many people use the subclassing method to create buttons sooooo

copper flume
#

let me test it

copper flume
merry cliff
#

if you do OOP it lets you do more things

upbeat otter
copper flume
#

👌

merry cliff
#

did it work?

copper flume
#

yeah

#

it think it is bad

#

too many buttons 😭

merry cliff
#

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

copper flume
#

and now I wanna make something cool

merry cliff
#

i mean.. don't fix it if it ain't broke 😉

radiant bough
#

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

merry cliff
#

otherwise I don't think self.current_page is defined

radiant bough
#

alright i did it and it works, thanks

ancient stump
upbeat mason
#

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?

shrewd apex
upbeat mason
#

forgot to say but im using nextcord

upbeat mason
#

will take less time than me figuring this out

upbeat otter
upbeat mason
#

i've already started to change the cogs manually so

upbeat otter
#

tf

upbeat otter
#

python is tripping yr

upbeat mason
#

real

upbeat otter
#

it would hve been easier to use the event

wanton current
#

!d discord.discord.ext.commands.on_command

unkempt canyonBOT
#

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.
upbeat mason
#

im using nextcord though remember

upbeat otter
wanton current
upbeat mason
wanton current
#

it's a 🍴

upbeat otter
#

trident and butter knife

upbeat mason
#

spork

rain hedge
shy eagle
#

hey there

#
NameError: name 'get_prefix' is not defined```
#

go this error

wanton current
#

where are you defining it?

twilit grotto
#

is your function get_prefix or is get_prefix a variable

shy eagle
#
  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

twilit grotto
shy eagle
#

kk

wanton current
#

no, you dont have a message to pass

twilit grotto
#

oh yeah that too

shy eagle