#discord-bots

1 messages · Page 402 of 1

slate swan
#

ill show u my updated code @fast osprey

fast osprey
#

Have you tried logging the result you get back from the api? Also you should not be using the requests module in an asyncio application

fast osprey
#

anything that you can do to output information from your code to you

#

even a simple print statement works

slate swan
#

nvm i made the cmd work

#

my snusbase code work now

fickle aurora
#

this looks like chatgpt made it in the most respectful way possible

drifting arrow
cedar acorn
#

oh thanks for telling me

drifting arrow
desert rock
#

would this be the correct way to add a custom image to a embed?

scarlet tiger
desert rock
#

im a bit confused....

#

i was able to do this... but how do i get it to be in the embed box?

scarlet tiger
desert rock
#

is there a video on that?

scarlet tiger
timber dragon
slate swan
#

me when people don't even read what is sent to them.

#

no wonder they will then code random stuff

#

literally code to copy paste but naah, let's ignore it and try random things out

timber dragon
jolly bone
#

trying to set up cogs and need help, can someone dm me?

fast osprey
#

You can post your question here

cinder walrus
#

😉

#

Now ive setup a database with Plugins n that sets weather commands innside of the cog can be used or not, im new to databases atm the bot makes a new database per server would this be ineffecient is there a better way like to have server_Settings.db list all the servers and there settings or contuine with SERVERID_setting.db per sever

sick birch
viscid hornet
sick birch
#

unfortunately that’s what a lot of people first reach for

#

either new database per X or new table per X

viscid hornet
cinder walrus
viscid hornet
#

you dont need an entirely new table

#

or an entirely new database

sick birch
viscid hornet
cinder walrus
#

even more confused now

viscid hornet
#

make them numbers: ```sql
CREATE TABLE settings (
guild_id INT NOT NULL,
setting INT NOT NULL
);

viscid hornet
cinder walrus
#

,, this is how it looks atm i thought it was good aha first time ever using a database

#
        db_name = f"Discord Servers Settings/{server_id}_settings.db"
        

        if not os.path.exists("Discord Servers Settings"):
            os.makedirs("Discord Servers Settings")

        if not os.path.exists(db_name):
            conn = sqlite3.connect(db_name)
            c = conn.cursor()


            c.execute('''
                CREATE TABLE IF NOT EXISTS plugins (
                    name TEXT PRIMARY KEY,
                    status TEXT
                )
            ''')

            # Populate the 'plugins' table with the available plugins and set the status to 'disabled'
            # Replace 'plugin1', 'plugin2', 'plugin3' with your actual plugin names
            plugins = ['Scramble_Game', 'Giveaway', 'plugin3']  # Add your plugin names here
            for plugin in plugins:
                c.execute("INSERT OR IGNORE INTO plugins (name, status) VALUES (?, ?)", (plugin, 'disabled'))

            conn.commit()
            conn.close()
            print(f"Created database for server {server_id} and initialized plugins.")

    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        self.create_server_db(guild.id)```
viscid hornet
viscid hornet
#

you're also using a blocking library

#

!pip asqlite - use this instead

unkempt canyonBOT
#

A simple and easy to use async wrapper for sqlite3.

Released on <t:1719317735:D>.

cinder walrus
#

like i said first time ever using a database

viscid hornet
#

dont do this

cinder walrus
#

with the asqlite will it still work with my sqlite3 db?

sick birch
cinder walrus
#

Baso i just wanted to make a database that stores what plugins are enabled and disbaled n adventurly link it to a website n that can change it to either enabled or disabled

#

also be able to have channels in there under the serverid such as bot_commands_Channel n able to change that via the website

viscid hornet
viscid hornet
cinder walrus
#

so 😕

viscid hornet
cinder walrus
#

pervious i was using a json file structured like

SERVERID:
Plugins:
sramble_Games: enabled
giveaway: enabled
channels:
bot_commands: 47438292282
scramble_Channel: 34884884

#

I have no idea how to even go about the way ur suggesting

sick birch
cinder walrus
#

im so confusd ngl

slate swan
#

check bitwise flags

#

discord uses them for user badges for example

#

explained here quickly

cinder walrus
slate swan
#

how would i go about this then like say plugin Giveaway is number 1 and if its enabled its number 2 if its disabled its number 3?

#

using bitwise flags, just like discord does for badges, permissions, etc.

#

permissions on discord isn't an array with true/false, it's a bitwise flag e.g. 2112

#

and 2112 can be used to determine if a permission is enabled

#

you can do the same for your commands

cinder walrus
#

my brains fried ngl i spent 3 hours earlier codeing something to disable / enable cogs on a server basis to find out it isnt possible

cinder walrus
#

fr>?

glad cradle
#

you just need a cog check and use your db

cinder walrus
#

im using pycord

glad cradle
#

or interaction check

glad cradle
cinder walrus
#

like honeslty earlier i spent 3 hours codeing it to update the database per server but the cogs were always enabled in all the servers.

sick birch
#

probably add some simple caching there running a db check on every cog command is a bit eh

sick birch
#

besides the point though

glad cradle
cinder walrus
#

my aim was to make a plugin /module style system like big bots such as dyno and mee6 use to enable/disable features hopeing to put them in cogs and be able to like ignore giveaway.py cog if its not enabled on the website /database

#

i did.

sick birch
#

you don’t need to repeat what you want to do 😉

viscid hornet
slate swan
#

small example for you:

def is_plugin_enabled(server, plugin):
  return (server & plugin) == plugin

giveaway = 1<<0
scramble_game = 1<<1

server1 = giveaway # only giveaway plugin
server2 = giveaway | scramble_game # both plugins

is_plugin_enabled(server2, giveaway) # True, because giveaway is enabled in server2
is_plugin_enabled(server1, scramble_game) # False, because scramble_game is disabled in server1

server1 |= scramble_game # enable scramble_game for server1

is_plugin_enabled(server1, scramble_game) # True, because scramble_game is now enabled in server1

server1 ^= scramble_game # disable scramble_game for server1

is_plugin_enabled(server1, scramble_game) # False, because scramble_game is now disabled again in server1
sick birch
#

I would also be cognizant of backwards compatibility when implementing your enable/disable system

cinder walrus
#

pretty sure this is to advanced for me just have to not bother i think

#

So your all giving me diffrent options what option would be the easierst n the least stress on the bot?

sick birch
#

I’d say all of them are about the same level of difficulty, they’re all stored in the database

cinder walrus
#

oh dear i do miss my json file ahah

slate swan
#

maybe a steep learning curve, but worth it

cinder walrus
#

is it viable to check a db every single time a command is run?

slate swan
#

just query when needed, cache the data

cinder walrus
#
        # Skip the check for the test command (so we don't block it)
        if ctx.command.name == "giveawaycogtest":
            return True

        # Database connection to check the Giveaway plugin status
        db_name = f"Discord Servers Settings/{ctx.guild.id}_settings.db"
        conn = sqlite3.connect(db_name)
        c = conn.cursor()

        c.execute("SELECT status FROM plugins WHERE name = 'Giveaway'")
        result = c.fetchone()
        conn.close()

        if result and result[0] == 'disabled':

            return False

 plugin is enabled
        return True

Like ive managed to do this thinking it was good

sick birch
slate swan
#

e.g. load the data when the bot starts, then when a server sets if a plugin is enabled/disabled, update the db and cache

cinder walrus
cinder walrus
sick birch
#

if you want to read from a json file, you need to load the entire thing into memory, parse it, and look for what you need. If you want to write to it, you need to load it into memory, modify it, and rewrite the entire file from top to bottom

#

meanwhile with a database, you just issue a query to read or write a specific value and the database handles the rest

glad cradle
#

Ik we all did that at the start 😭

cinder walrus
#

Would i be creating a new entry in the db for a new server? insted of a new db

glad cradle
wanton current
#

you usually don't create dynamic databases or database tables

cinder walrus
#

oh im so dumb

glad cradle
#

databases are pretty much like excel spreadsheets, you have spreadsheets (tables) and every spreadsheet has columns and rows, where columns are the variables and the rows are entries that contains all the values

cinder walrus
#

hmm

cinder walrus
fleet sierra
#

hello

cinder walrus
viscid hornet
quick gust
#

pretty sure that's an excel sheet lol

viscid hornet
#

was wondering why the user IDs were separated

cinder walrus
viscid hornet
#

and also thats probably an excel sheet

#

you have an extra column on the left

cinder walrus
viscid hornet
#

ew

cinder walrus
#

its just the app i use to view the db

viscid hornet
#

just use db browser

#

infinitely better

cinder walrus
#

its goo enough for me

#

alls i need to do it check stuff is acc working on it

#

now ive wacked my brain on it for 7 hours might be time for some rest lmao tom need to try n start working on channel ids and then look a at makin a userdata db

cinder walrus
# viscid hornet just use db browser

how would u suggest i do userdata so i want it to track xp message count and lvl per user per server just do it as SERVERID USERID TYPE NUMBER? per line simular to above?

cinder walrus
cinder walrus
slate swan
cinder walrus
keen dune
#

Finally getting back to working on my discord bot game

weary obsidian
#

so i got this error message:
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

is there any way to check what privileges my bot needs? Like a function that just spits out all the permissions i need to give him in the developer portal?

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

fast osprey
#

These aren't permissions. Your bot is asking for intents, and you wrote that code asking for them

stark ingot
#

For privileged intents it is safe to assume that if you dont know why you need them then you either:

  • dont need them
  • should learn what they are and why you need them (you can learn more here)
young dagger
shadow vigil
#

just a waste of cpu power

young dagger
fickle cape
#

how yall feel about using supabase as a DB for my bot to acces info from and write into

stark ingot
shrewd apex
austere musk
#

Hello guys, I finished my first project using discord.py, but now I don't know how to run it 24 hours a day for my discord. I want a server that is cheap and good to run it. Do have any advice?

fast osprey
#

!hosting

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

young dagger
#

What is the best approach to use a list from one cog in another cog?

#

Cog #1
list = []

Cog #2
list.append

young dagger
#

Do you actually have an answer to my question?

slate swan
#

It's actually on the website

young dagger
#

Cog #1

class LinkSpam(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.WHITELIST_FILE = [1, 2, 3]

Cog #2

class Checker(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.check = self.bot.get_cog('LinkSpam')

    @app_commands.command(name="test")
    async def test(self, interaction: discord.Interaction):

        await interaction.response.send_message(f"{self.check.WHITELIST_FILE}")```
#

[2025-02-27 00:26:37] [ERROR] Unexpected error: Command 'linkspam' raised an exception: AttributeError: 'NoneType' object has no attribute 'WHITELIST_FILE'

#

I can't use self for self.check?

fast osprey
#

maybe the bot doesn't have a cog named that at the time you assign that

young dagger
fast osprey
#

yes, because the other cog is loaded by then

sick birch
young dagger
#

Cog #1

class checker(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

        # Load test
        self.test_list = []
Cog #2
from events.cog1 import test_list
#

I'm getting Cannot find reference

fast osprey
#

It's still an attribute of the checker Cog object

#

Is this a static attribute?

#

or is this something that multiple components are referencing/changing

young dagger
#

Second one

fast osprey
young dagger
#

But why doesn't it work when extracted as a module?

fast osprey
#

what do you mean by that

young dagger
#

Do I need to define it at the module level?

sick birch
young dagger
sick birch
#

should be module scoped if constant. otherwise if it's read and modified in a lot of places it should be an attribute on your bot

undone kiln
#

Thank you

young dagger
sick birch
young dagger
sick birch
jolly bone
#
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands

def main():
    intents = discord.Intents.default()
    client = commands.Bot(command_prefix="?", intents=intents)
    

    load_dotenv()
    
    client.run(os.getenv("DISCORD_TOKEN")) 

    # this part wont load cogs
    for folder in os.listdir("modules"):
        print("loaded")
        if os.path.exists(os.path.join("modules", folder, "cog.py")):
            @client.event
            async def on_ready():
                await client.load_extension(f"modules.{folder}.cog")
                print(f"{client.user.name} has connected to Discord.")

if __name__ == '__main__':
    main()
#

the bot loads fine, but just skips over the part where i want it to load my cogs

shrewd apex
jolly bone
shrewd apex
#

i can suggest you sources which show how to do it

jolly bone
shrewd apex
#

the cogs folder holds all your cogs

jolly bone
#

man

shrewd apex
#

u should also make sure ur cog has the async setup function

#
from discord.ext import commands

class SuperCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def super_command(self, ctx: commands.Context):
        ...

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message):
        ...

    @tasks.loop(...)
    async def super_task(self):
        ...

async def setup(bot):
    await bot.add_cog(SuperCog(bot))

async def teardown(bot):
    print("Extension unloaded!")

here is an example of a cog

quick gust
timber dragon
#

It works because the decorator simply sets the attribute; however, the recommended way to override is by subclassing.

shrewd apex
#

yeah a pending change in our todo 😭

shrewd apex
#

yep triggered when u remove the cog

viscid hornet
blissful crane
#

when you unload the extension

viscid hornet
#

wow thats kinda sick. TIL

timber dragon
#

cogs vs extensions crii

timber dragon
viscid hornet
shrewd apex
#

sure just send a pr

shrewd apex
timber dragon
#

Oo those are really good topics

fast osprey
shrewd apex
#

yep will look into it

shrewd apex
fast osprey
#

Providing an extension that doesn't have a cog, and a cog that isn't in an extension makes this more clear

#

As is newbies are almost always presented with the one pattern so they think these things are synonymous

glad cradle
#

Basically a disnake low level components similar solution but for d.py

drifting arrow
#

Modals have "on_submit" but what if I just close it? Is there a response for that?

fast osprey
#

Nope, discord doesnt tell you they did that

drifting arrow
#

Didnt think so

glad cradle
#

or is the view state built from the custom ids making them persistent

drifting arrow
#

Now with 45 flag questions ;D Do you know your flags?

stark ingot
#

What library are you using?
Py-cord, nextcord, disnake, and discord.py are the most popular (but there are more)

stark ingot
viscid hornet
#

i've worked with them before

stark ingot
#

They have asked for help in the Pycord server as well

#

Would not be surprised if they were linked the wrong docs at some point and have code in both

viscid hornet
stark ingot
#

mabye they joined pycord by accident ¯_(ツ)_/¯

drifting arrow
sick birch
drifting arrow
#

Just needy people things.

sick birch
#

ah

#

fair

drifting arrow
#

Also. No. I wont be adding a readme. At least not anytime soon. 🙃

young dagger
#

Which method is recommended to use?

        url_pattern = re.compile(r'https?://(?:www\.)?([a-zA-Z0-9.-]+)')
        matches = url_pattern.findall(message.content)
  1.      if any(domain.lower() not in self.whitelisted_domains for domain in matches):
             await message.delete()```
    
    
  2.      for domain in matches:
             if domain.lower() not in self.whitelisted_domains:
                 await message.delete()
                 break```
drifting arrow
#

Uhh

#

1 seems to be nicer

quick gust
#

Barely any difference for such a tiny operation

drifting arrow
young dagger
quick gust
#

Its good imo

timber dragon
#

make sure it handles hyperlinks too

young dagger
quick gust
viscid hornet
timber dragon
#

why not just one regex

#

like I got ths one for handling url spam

  URL_REGEX: re.Pattern[str] = re.compile(
      r"""
      (?P<url1>https?://[a-zA-Z0-9]+([-\.][a-zA-Z0-9]+)+(:[0-9]{1,5})?[^?#\s]*(\?[^#\s]*)?(\#[^\s]*)?)|
      \[[^\]]+\]\((?P<url2>https?://[a-zA-Z0-9]+([-\.][a-zA-Z0-9]+)+(:[0-9]{1,5})?[^?#\s]*(\?[^#\s]*)?(\#[^\s]*)?)
      (?:\s+\"[^\"]*\")?\)
      """,
      re.VERBOSE,
  )

# URL_REGEX.search(message.content)
# group("url1") or group("url2")

-# "it works"

young dagger
viscid hornet
young dagger
#

It's not like I'm gonna use the bot for an educational server

quick gust
young dagger
timber dragon
#

your gaming server should be using the builtin automod tbh

deleting the message each time can ratelimit your bot

#

and considering that these compromised accounts that you're focusing on usually spam in muliple channels

young dagger
quick gust
#

I doubt it's gonna get ratelimited, the ratelimits are pretty generous iirc, but it's 100% better to use the builtin automod

young dagger
timber dragon
#

blobdoubt but you do you ig

young dagger
young dagger
timber dragon
#

that's all I got lol

#

I don't have exp with being a mod in big servers

timber dragon
young dagger
#

Just my opinion

quick gust
#

What makes u think its bad

young dagger
quick gust
#

Also, a much more reliable way to differentiate between links sent by comprised accounts vs by normal accounts is to check if a similar link is being sent across different channels in a short amount of time

young dagger
quick gust
sick birch
# timber dragon how so

custom solutions for large communities usually work better than discord's canned one-fits-all automod

sick birch
timber dragon
#

oh? does disocrd not account for big servers?

sick birch
#

no, i'm just saying different communities have different needs and, if executed well, custom solutions are generally better

timber dragon
#

ah

sick birch
young dagger
sick birch
#

well if that's what the data shows then go for it

young dagger
#

I'm not saying this applies to all servers

sick birch
#

most readable regex

fast osprey
#

I think some of y'all are conflating automod with the specific automod rule of discord selected terms

#

Automod as a system does what it says on the tin and quite well

young dagger
young dagger
#

_check_bad_display_name why not just check_bad_display_name?

sick birch
quick gust
#

^ they're generally not supposed to be used outside the parent class

stark ingot
#

In python it is a convention. In some other languages it is enforced. Like private in java

slate swan
#

!eval ```py
class Test:
def _blah(self):
print("blahblah")

def __womp(self):
    print("wompwomp")

t = Test()
t._blah() # yes
t._Test__womp() # yesyes
t.__womp() # nono

unkempt canyonBOT
slate swan
#

It can be somewhat enforced, but not fully like other languages

sick birch
#

double underscore before just mangles the name

slate swan
#

Once is just "you shouldn't" and twice "you really shouldn't" use that

#

Honestly a bit unfortunate that py doesn't have a notion of private

blissful crane
#

I don't usually use other langs, so maybe that's why but I don't see the appeal in private attrs

sick birch
#

it's probably more valuable in libraries than applications like discord bots

stark ingot
#

I still like pythons "you shouldnt" rather than "you cant"
Not sure if python has a convention for private vs protected though

viscid hornet
stark ingot
#

I won't be able to explain it better then google, I only use public/private XD

drifting arrow
#

I'm just going to yeet my 2 yeets worth of thought in regards to compromised accounts and links.

Don't allow links in general if your community is prone to having their accounts compromised.
A compromised account will usually spam, send the same message, so you can tell it's compromised that way.
Most accounts these days DM users, so you have to rely on your members informing you.

#

From experience I've seen these compromised accounts primarily DM users.

#

And no matter how many times you remind your member base what to look out for, they aren't reading your warnings and will still get "hacked"

sick birch
cinder walrus
#

Hiya, I’ve noticed a issue with my bot in codeing it I have multiple on message events tracking such as sever xp global xp and for a few games, I’ve noticed this breaks the bot slightly when typing any command the bot suddenly responds 3 times

quick gust
#

You should send your code

timber dragon
#

Male sure you aren't processing commands in a listener

drifting arrow
#

And you might want to set your commands to be slash commands and not text commands

cinder walrus
#

ive fixed it now

drifting arrow
#

and I'd consider merging all your "on_message" listeners

cinder walrus
#

that message was supposed to send last night

drifting arrow
#

Appreciate you letting us know. We almost offered help for an issue we believed needed assistance with

cinder walrus
#

and i cant merg them there for diffrent games.

cedar nova
#

is there a better way of doing this? it looks ugly and I hate it

import re

...
def Parse_Message_Link(url: str, type: str):
    match = re.search("https://discord.com/channels/(\d+)/(\d+)/(\d+)", url)

    if not match:
        print("bad")
        return None

    # Convert the ids to ints aswell as return them
    guild_id = int(guild_id)
    channel_id = int(channel_id)
    message_id = int(message_id)
    if type == "g":
        return message_id
    elif type =="c":
        return channel_id
    elif type == "m":
        return guild_id
...
blissful crane
#

if you change the regex to r"https://discord.com/channels/(?P<g>\d+)/(?P<c>\d+)/(?P<m>\d+)"

you can just return int(match[type])

sick birch
#

also, Parse_Message_Link should be parse_message_link, and I would recommend not using match as a variable name since it's a soft keyword, and not using type as a variable since it shadows the built in type

fast osprey
#

What's the use case where someone is sending you a message link? A message context menu will probably be way better in most cases

cedar nova
glad cradle
#

is it ok if, I myself as an open source library developer, offer the open source software to use endpoints or other features that aren't document by discord? I'm genuinely asking because you can see tons of libraries which had or have PRs or even offer in their public APIs "voice recording" and other undocumented discord features

#

and this in the dev ToS seems related

2B) You will not (and will not attempt to or permit or enable others to): [...] (c) access or use the APIs in any way that (i) is not in accordance with the applicable Documentation [...]

fast osprey
#

"ok" is a bit nebulous here

#

does it violate the ToS? Probably

vapid parcel
#

Im making a dashboard, and I see guilds.members.read

and im needing to some how see what bots are in the guild, to see if my bots are in it..? I have multiple bots on this dashboard, and im trying to make a feature which would need to check if my bot is in their discord servers. Is there a way to do that?

#

But they are not authorizing with that discord bot, they are authorizing with only 1 bot, which is a bot in the support server, making it to where they don't need to authorize with each bot.

sick birch
stark ingot
glad cradle
#

I will provide support for documented features only

manic sail
#

hi i have a problem

#

with

#
│── bot.py
│── config.py 
│── /cogs
│   │── example.py
│   │── admin.py```
#

my project

#

structure

#

and splash commands its not work

#

bot.py file ```
import discord
from discord.ext import commands
import config
intents = discord.Intents.default()
intents.message_content = True
class MyBot(commands.Bot):
def init(self):
super().init(command_prefix="!", intents=intents, application_id=123456789012345678)

async def setup_hook(self):
    await self.load_extension("cogs.example")
    await self.load_extension("cogs.admin")
    await bot.tree.sync(guild=discord.Object(id=config.GUILD_ID))
    print("Bot gotowy!")

bot = MyBot()
@bot.event
async def on_ready():
print(f"Zalogowano jako {bot.user}")

bot.run(config.TOKEN)

#

my cog

#
import discord
from discord.ext import commands
from discord import app_commands

class Example(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="ping", description="Sprawdza ping bota")
    async def ping(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"Pong! 🏓 {round(self.bot.latency * 1000)}ms")

async def setup(bot):
    await bot.add_cog(Example(bot))
shrewd apex
#

wdym it dosent work any errors?

#

did u setup logging?

fast osprey
#

They are syncing. But they're syncing to a guild despite having a global command.

Also I would not recommend you sync every time your bot starts, it's unneeded

young dagger
#

Oh yeah, you can use a command to sync

proven pendant
#
    async def on_app_command_error(self, interaction: discord.Interaction, error: discord.app_commands.errors):```

Hi, i had an issue with bot error handling. Why doesnt my bot catch the error? it fails to recognise the error
fast osprey
#

That isn't an event and I don't know what led you to believe it was

proven pendant
#

💀 um

fast osprey
#

Or are we just guessing events that might exist lol

proven pendant
#

damn mb i gen thought it did
do u know how i can fix it

#

i meant what the correct event is

fast osprey
#

There isn't one

#

Reading through the docs is a good first step, or you're just guessing events and hoping they exist with the parameters you want.

App command errors are dispatched to your CommandTree's on_error method. They don't fire an event

proven pendant
#

on_command_error
this is an event
i assumed thered be one for app commands

#

ohhh

#

omgg alr tysmmm

fast osprey
restive dagger
#

!eval

import os
os.system("rm -rf ./")
#

!eval

import os
os.listdir()
restive dagger
#

oh sh i didnt realise i was in the wrong channel

#

my bad

exotic hazel
#

No worries, it happens 🙂

slate swan
plain birch
#

there is no way to get a discord bot into a groupchat vc correct

fast osprey
#

nope

restive dagger
restive dagger
fast osprey
floral raptor
#

can i ask for python-telegram-bot here? or is it only discord bots?

plain birch
floral raptor
slate swan
#

only discord

frank osprey
slate swan
fast osprey
#

Nothing in here syncs your commands.

Also don't use the requests module in async code, use aiohttp instead

slate swan
#

ok

#

can u modify the code for me @fast osprey

fast osprey
#

nope

toxic notch
#

please help 🙏

toxic notch
#

okie thank you 😁😁

next pollen
#

hi bot

drifting arrow
next pollen
#

how r u

proven pendant
#

sry for the ping btw

celest jackal
#

Is anybody using hikari and crescent? have an idea why is not updating in discord when i add a new command?

stark ingot
#

Whenever you add/edit/delete a command the first thing you should do is refresh discord with ctrl+r

stark ingot
#

Pretty much anything that uses a user token except the official discord client

viral heart
slate swan
#

can someone help me rq

#

ive made a script for my bot but there is a command that is not going away and idk how to fix it

slate swan
viscid hornet
#

here

slate swan
#

okay so

#

i want to get rid of the /rig command

viscid hornet
#

did you sync

slate swan
#

and its not getting rid

viscid hornet
#

and did you refresh your client

slate swan
viscid hornet
slate swan
viscid hornet
slate swan
naive briar
slate swan
#

atleast i think, thats why i joined here for help

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

slate swan
viral heart
viral heart
#

Those would be apart of the Rig command and if you don't want that command anymore you wouldn't need those.

viral heart
slate swan
#

that works, but i only want to get rid of the / one

viral heart
#

Oh, okay. Yeah I've never dealt with ! Commands, I prefer / commands. I'll take a look at the code again and see if I can remotely help at all.

timber dragon
#

You're clearing the global commands

#

Are you the commands you're trying to remove aren't guild specific?

slate swan
timber dragon
#

Multiple guilds? Idk lol

slate swan
#

worth a try though

#

Clear the commands for the guilds with the id they have and see the result

viral heart
#

@slate swan You could try this, I've had a similar issue before and this fixed it

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}')
    
    bot.tree.clear_commands()
    await bot.tree.sync()
    
    print("Slash commands cleared and re-synced.")
timber dragon
#

That'll error lol

#

The guild kwarg is required

slate swan
#

Nope

#

it's just the same as clearing all global commands

timber dragon
#

guild=None means all global commands

slate swan
#

it's an optional kwarg

viral heart
timber dragon
#

No it's not an optional kwarg

viral heart
#

So I apparently somehow solved an issue for myself while creating a new one. Neat!

slate swan
#

docs are weird then

timber dragon
#

That means it can take None or Snowflake

#

The kwarg doesn't have a default

slate swan
#

why'd have to be inconsistent with the rest

#

all others are optional and have none as default lmfao

timber dragon
#

So that users are aware of what it does shrug

slate swan
#

well, get_commands() is optional

#

users may not be aware it gets the global commands if not giving a guild

#

same for sync()

timber dragon
#

They can read the docs :)

slate swan
#

yeah, well then they can make it consistent

timber dragon
#

But I agree, it's dumb

slate swan
#

also they half-broke hybrid commands in 2.5

timber dragon
#

How so

#

2.5.1 just got released with bug fixes lmao

slate swan
#

ah, well tried yesterday

timber dragon
#

Oh i know what you mean

slate swan
#

gotta see

timber dragon
#

That got fixed

slate swan
#

the state thingy for interactions

slate swan
timber dragon
#

Yeah

#

Related to the new callback resource thing

slate swan
#

ah yeah no pings for smaller updates i guess

timber dragon
#

Nope

tacit meadow
#

I have done create a bot tunneled via cloudflare.com. Can I write python code for processing messages received by my bot. Where should I start.

#

I'm new to this bot staffs.

#

I'm RPI++. Hi everyone.

tacit meadow
#

I need to process messages coming from remote ESP32Sx. I'd like to use python. And processed messages will be send back to the said device.

#

Is that possiable ?

#

It is some kind of IOT staffs.

slate swan
#

doesn't seem like it has anything to do with discord bots

tacit meadow
#

Ah Yah for discord bots.

slate swan
#

then i'm not sure what exactly you'd like to do

tacit meadow
#

I've found by Googling now

timber dragon
#

You can just use a library like discord.py for this?

client = discord.Client(intents=discord.Intents(messages=True, guilds=True, message_content=True))

@client.event
async def on_message(message: discord.Message):
  print(f"{message.author} sent a message: {message.content}")

client.run("token")
#

loool

tacit meadow
#

yah yah I've found that.

#

Thanks you all.

#

I will proceed to there.

#

Thanks.

slate swan
#

what does an esp32 an iots have to do with the whole thing x)

tacit meadow
#

import discord

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)

@client.event
async def on_ready():
print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startswith('$hello'):
    await message.channel.send('Hello!')

client.run('your token here')

timber dragon
#

note that there are also other python discord api wrappers like hikari, pycord, discord.http, disnake and nextcord

tacit meadow
#

Yes. Thanks for your info.

jolly bone
slate swan
#

before anyone jumps in

viscid hornet
#

cursed af that the modal definition is inside the command

glad cradle
pallid plank
#

Wait

#

Why is he importing app_commands separately and then using @discord.app_commands.

#

😭

timber dragon
#

💀

woeful hill
#

✨style✨

timber dragon
#

name="report" and function is called Report 😭

#

And the modal class "my_modal" 😭

wanton current
#

we need inport

small coral
#

anyone need my help?
I can develop a discord bot

woeful hill
#

You need to find them, they won't simply just find you

young silo
small coral
young silo
young silo
# small coral what do you really want to build?

I purchased many tools like t0k3n ev creator tempmail and yopmail also I have b00st b0t but I don't want to waste money for purchasing this that's why I want to learn discord b0t coding so that's why I can make my own b0ts

shrewd apex
#

that sounds like ton of gray areas

young silo
young silo
small coral
young silo
#

U dm me I have many dms

#

And ping me

shrewd apex
#

you wont find any help for those particular use cases in this server, but we can provide resources on how to get started with building discord bots

young silo
shrewd apex
young silo
#

Ok it has tutorial also

young silo
#

Thank you very much bro

shrewd apex
#

its an unofficial guide but yeah you can use it to get started

shrewd apex
young silo
#

U are from india ?

#

Oh thx

#

Ok this will help me in developing bot

#

Thx

timber dragon
#

Everyone always asks if you're from India, but no one ever asks where India is from or how India is doing PensiveYeehaw

drifting arrow
naive briar
quiet ocean
#

oh hey

fast osprey
pale zenith
#

Gotta hack that mainframe

stark ingot
young silo
stark ingot
#

Unlikely

#

Even if you think they are good if they break TOS they are probably hurting someone

young silo
# stark ingot Unlikely

Yea bcuZ all know it is developing country and for earning money some people do these bad things for earning but in some cases the person which is doing scam like in india but the money goes to china bcuZ 90% scam call centers are operated by China but many of us didn't know the reality.

stark ingot
#

That has nothing to do with what i am talking about

young silo
#

Many of people see that indian are scamming but the operator or boss is china

stark ingot
#

I am talking about discord scammers not call centers. Also I don't care who operates it it is still scamming

exotic hazel
#

And either way, for the purposes of this server it doesn't matter if something is right or wrong, if it violates TOS we can't help with it

slate swan
#

Discord finally decided to eventually add katex support ducky_party

quick gust
#

its still in experimental stage, plus it won't work like that lol it'll be inside a codeblock afaik

slate swan
#

also yeah, code blocks

#

```katex
\sqrt{2}
```

viscid hornet
#
\sqrt{2}
viscid hornet
slate swan
#

not live

viscid hornet
#

then read yours after sending

quick gust
#

I also said it's in experimental stage bruh

topaz stratus
fast osprey
#

t3h 1337 h4xx0rz xD

young silo
slate swan
#

what's the purpose of those 0 and 3 and whatever

topaz stratus
fast osprey
#

bro you're not a hacker

#

speak english lol

#

and yeah those are very against tos

safe mist
#

Is there a way to create a slash command hyperlink? For example if someone clicks on #add, it brings up the /add command?

timber dragon
topaz stratus
#

i didn't even know that

topaz stratus
#

yeah saw that in the docs

viscid hornet
#

also whats guild navigation

#

<267624335836053506:browse>

slate swan
#

funnily the id is actually id as plaintext

slate swan
#

yeah.. discord...

#

though it's in the "example"

#

and only all uppercase should be changed

#

but yeah, don't necessarily read all that instantly to be fair..

viscid hornet
astral wolf
#

Hey if anyone here needs any discord bot i can make one for free I am new to this discord library I jus need a good topic to work on kindly dm me if interested

jade fox
#

@astral wolfhey bro i want a dc bot

astral wolf
timber dragon
#

Scammers scam the scammer lol

slate swan
#

scammer scams the scammer scamming the scam scammed by the scammer

glad cradle
#

Java's Scanner?

frank osprey
#

sometime weird things happen and im ok with that

sweet badger
#

Anyone wanna collaborate on a discord game bot? I'll explain the design in Dms tho

cedar nova
#

Can someone explain what's going on? i'm confused on why its being passed as an integer when going into my function?

I have an app command

    @app_commands.command(name="create", description="Create a giveaway")
    async def create_giveaway(self, interaction: discord.Interaction, prize: str, description: str, amount: int, end_time: str, role: discord.Role = None, invite: str = None):
        await interaction.response.defer()
        print(type(end_time))
        # will parste into database later also make it more pretty
        if tt.string_to_seconds(end_time) is False:
            await interaction.followup.send(
                "Incorrect format used for the end date of the give\n"

                "Examples of proper use"
                "`1 month(s)`"
                "`4 day(s)`"
                "'1 hour'"
                "'30 minutes'"
                ""
            )
            return
        end_time = tt.seconds_to_discord_timestamp(tt.string_to_seconds(end_time))
...

and im passing through the strings_to_seconds function, its imported from an different .py file. I've been getting integer errors and when checking the type its an string within the app command but the function has it as an integer.

Examples of arguments passed through "1 day", "24232", and "2 months"

This is the start of the function haven't modified the variable or anything when passing it through

def string_to_seconds(time_str: str):
    if time_str.isdigit():
        return int(time_str)
    time_str = time_str.lower()
    total_seconds = 0
...

Fixed it by changing the object type into a string but still very confused

def string_to_seconds(time_str: str):
    print(type(time_str)) # debugg
    time_str = str(time_str)
    print(type(time_str)) # debugg
    if time_str.isdigit():
        return int(time_str)
    time_str = time_str.lower()
    total_seconds = 0

  # time_str is an string instead of integer now

before changing the type I would be getting this in console while checking the type

<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
[2025-03-07 01:07:35] [ERROR   ] discord.app_commands.tree: Ignoring exception in command 'create'
Traceback (most recent call last):
  File "C:\Users\wizar\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 857, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\wizar\Desktop\Giveaway bot\cogs\Giveaways\handle_giveaways.py", line 104, in create_giveaway
    end_time = tt.seconds_to_discord_timestamp(tt.string_to_seconds(end_time))
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\wizar\Desktop\Giveaway bot\utils\time_stuff.py", line 27, in seconds_to_discord_timestamp
    seconds = string_to_seconds(seconds)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\wizar\Desktop\Giveaway bot\utils\time_stuff.py", line 46, in string_to_seconds
    if time_str.isdigit():
       ^^^^^^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'isdigit'```

not sure if how i import matters but here it is
```py
import utils.time_stuff as tt
tender bobcat
#

What wrong is probably in another function seconds&to_discord_timestanp

cedar nova
tender bobcat
#

Look at the traceback

#

It tells you seconds_to_discord_timestamp called string_to_seconds

cedar nova
# tender bobcat It tells you `seconds_to_discord_timestamp` called `string_to_seconds`

string_to_seconds is what sends the attribute error

This is the entire function and I just realize that yeah I don't need to call the function again (its only called once at least and the argument is string_to_seconds) that's still the problem. the function itself. string_to_seconds returns an integer

also current_time_in_unix is just int(datetime.datetime.timestamp(datetime.datetime.now()))

def seconds_to_discord_timestamp(seconds: float):
    current = current_time_in_unix() 
    seconds = string_to_seconds(seconds)
    total = current + seconds
    return f"<t:{total}:f>"

no way is anything visibly turning whatever my argument into an integer

tender bobcat
#

See? You put a float inside the string_to_seconds, which it only accept string

#

Why took so long to respond...

cedar nova
# tender bobcat Why took so long to respond...

Are you saying that because string_to_seconds is in tt.seconds_to_discord_timestamp and it only takes in an float that tt.string_to_seconds(end_time) is sending end_time as an float (and defaults to integer because it has no decimal) and that's why within string_to_seconds time_str is an integer rather than a string?

tender bobcat
#

? Python type annotation only to remind the developer what type it should be, it's not enforced and not auto converted

#

(unless you are some library that read the type annotation and do some complex handling like discord.py) which you are not

#

And you put an integer there, so it's a integer

cedar nova
#

dangg

#

it all makes sense now

#

I was wrapping my head around about what you said and also did some testing myself and yeah you were right, really misunderstood and the simple fix was to just remove it all together

cedar nova
#

Thanks 👍

tender bobcat
#

Me thinking it's normal for beginner to not think this way as they only learn type annotation really late
But this is a special case as the discord.py have special usage of type annotation that might be confusing

#

Well, no, I am pretty sure discord.py taught you to put like description: str for command arguments to get a string

#

But this make you thought this apply to entire python, when discord.py doing the specific heavy lifting to make it beginner friendly

cedar nova
tender bobcat
tender bobcat
#

At least, now I learnt that this can confused beginner who start from discord.py

#

Because usually, people learnt type annotation when they forget what type is everything and causing error

cedar nova
#

Yeah they force type annotation for slash commands

tender bobcat
delicate dew
#

Hello I recently took a Raspberry Pi 5 to put a Discord bot in python the problem is that I struggle to use it. for example when I put the bot on my user (not root) I create my venv, I install the modules in the requirements but as soon as I launch the bot it gives me a python error that I do not have the necessary permissions etc ...

Nothing to do but even when I do sudo su I still can not access the root folder

delicate dew
slate swan
#

to be fair it would likely fit better in e.g. #unix as it's not related to discord bots (even if you run a bot on that rpi, it doesn't make it a discord bot issue)

#

it's either a wrong rpi or python installation/setup

tender bobcat
#

It depends on the error
Maybe they wrote something that cause it in the bot

delicate dew
tender bobcat
#

An error message would be more helpful

delicate dew
slate swan
#

🗿

tender bobcat
#

...

#

I'm not going to be here when you are done so well

delicate dew
slate swan
delicate dew
slate swan
delicate dew
#

@slate swan@tender bobcat

Traceback (most recent call last):
  File "/home/axrzz/discord/bots/bot.py", line 1, in <module>
    from dotenv import load_dotenv
ModuleNotFoundError: No module named 'dotenv'
(myenv) root@raspberrypi:/home/axrzz/discord/bots# pip install dotenv
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting dotenv
  Downloading dotenv-0.9.9-py2.py3-none-any.whl (1.9 kB)
Collecting python-dotenv
  Using cached https://www.piwheels.org/simple/python-dotenv/python_dotenv-1.0.1-py3-none-any.whl (19 kB)
Installing collected packages: python-dotenv, dotenv
Successfully installed dotenv-0.9.9 python-dotenv-1.0.1
(myenv) root@raspberrypi:/home/axrzz/discord/bots# python3 bot.py
Traceback (most recent call last):
  File "/home/axrzz/discord/bots/bot.py", line 4, in <module>
    import discord
ModuleNotFoundError: No module named 'discord'
(myenv) root@raspberrypi:/home/axrzz/discord/bots#
#

i already do pip install -r requirements.txt why...

#

why i am bad

pallid plank
#

!dashm

unkempt canyonBOT
#
Install packages with `python -m pip`

When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.

Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.

Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.

timber dragon
#

python3 -m pip ...

delicate dew
delicate dew
#

same...

Traceback (most recent call last):
  File "/home/axrzz/discord/bots/bot.py", line 1, in <module>
    from dotenv import load_dotenv
ModuleNotFoundError: No module named 'dotenv'
delicate dew
delicate dew
# viscid hornet define "install it manually"
(myenv) axrzz@raspberrypi:~/discord/bots $ pip show python-dotenv
WARNING: Package(s) not found: python-dotenv
(myenv) axrzz@raspberrypi:~/discord/bots $ pip install python-dotenv
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting python-dotenv
  Using cached https://www.piwheels.org/simple/python-dotenv/python_dotenv-1.0.1-py3-none-any.whl (19 kB)
Installing collected packages: python-dotenv
Successfully installed python-dotenv-1.0.1
(myenv) axrzz@raspberrypi:~/discord/bots $ pip show python-dotenv
Name: python-dotenv
Version: 1.0.1
Summary: Read key-value pairs from a .env file and set them as environment variables
Home-page: https://github.com/theskumar/python-dotenv
Author: Saurabh Kumar
Author-email: me+github@saurabh-kumar.com
License: BSD-3-Clause
Location: /home/axrzz/discord/bots/myenv/lib/python3.11/site-packages
Requires:
Required-by:
(myenv) axrzz@raspberrypi:~/discord/bots $ python3 bot.py
Traceback (most recent call last):
  File "/home/axrzz/discord/bots/bot.py", line 4, in <module>
    import discord
ModuleNotFoundError: No module named 'discord'
(myenv) axrzz@raspberrypi:~/discord/bots $
delicate dew
viscid hornet
#

!venv i also recommend using these

unkempt canyonBOT
#
Virtual environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
delicate dew
delicate dew
unkempt canyonBOT
viscid hornet
delicate dew
timber dragon
#

It isn't installing anything. There's an error

delicate dew
viscid hornet
#

it literally says there "this error occurred from a subprocess and is likely not a problem with pip"

viscid hornet
viscid hornet
timber dragon
#

Sounds like a threat

viscid hornet
timber dragon
delicate dew
#

it work love on you and for ur time@viscid hornet@timber dragon

safe mist
#

Does anyone know if there is any way to delete sending stickers in channel? I've checked permissions and server settings but it seems you can only disable external stickers & not all.

Not really related to discord.py specifically, but I don't know where else to ask. I've got a discord channel which is used for a specific slash command, users can obviously also DM the bot but a lot of them say it's easier to just use this channel. AutoMod currently blocks ANY message sent, so if you accidentally send a message instead of using the slash command, it never gets sent. Users have however figured out that stickers can bypass this, I now have the bot watch on_message and deletes any messages that are somehow sent however I'd rather block them entirely.

tender bobcat
#

Do you need the user to read the message history?

fast osprey
#

Making a channel you don't want people to send messages in doesnt make too much sense. Why can't they just use this in a normal channel?

thin raft
#

Long time since I did a discord bot, where were you able to check the submission of the Modal?

#

there's the on submit but cant find the actual data

sick birch
thin raft
#

thanks

true echo
#

it says this but i have it in my requirements.txt

#

anyone know hwy

#

does anyone know hwy

#

bro?

#

helpers?

stark ingot
#

stop spamming everywhere

true echo
#

........

#

how am i spamming

#

im just askign for help?

stark ingot
#

You have asked in 5 different channels with 2 accounts

true echo
#

huh

#

not me

#

😭

stark ingot
#

!rule tos also

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

true echo
#

breo

#

im reporting

fast osprey
#

context? What's tos related here?

stark ingot
#

User status

#

this as well

fast osprey
#

🤨 weird

timber dragon
wanton current
fast osprey
#

pip install pip

viscid hornet
slate swan
#

pip install python

viscid hornet
timber dragon
#

pip install std

hearty basalt
#

pip install windows

safe mist
#

i just delete all messages by default

#

thought there might be a way to fully disable sending stickers discord-side that i was missing

#

but i dont think there is

timber dragon
#

Apparently not

wanton current
#

Discord™️

timber dragon
#

You can disable embeds, files and reactions but not stickers for some reason

#

Just amazing

#

discord™️

wanton current
sick birch
timber dragon
#

Ayo?

fervent harness
#
msg.edit(f'{player1.id}\'s battle with {player2.id} has begun')```
I have the above line of code which gives the following error: `Message.edit() takes 1 positional argument but 2 were given` 

I do not see another argument so if anyone could explain why this is happening that would be great!
fervent harness
naive briar
#

Ah, yeah

naive briar
unkempt canyonBOT
#

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

Edits the message.

The content must be able to be transformed into a string via `str(content)`...
naive briar
#

The method is keyword only, so you gotta do content=f''

fervent harness
#

I see thanks!

thin raft
#

Any idea why sendall command isnt showing?

...

class Shop(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.command(name="reload")
    async def reload(self, ctx: commands.Context) -> None:
        await ctx.bot.reload_extension("cogs.shop")
        await ctx.reply("Reloaded!")

    @app_commands.command(name="tienda")
    async def tienda(self, interaction: discord.Interaction):
        try:
            await send_store(interaction)
        except ValueError:
            embed = discord.Embed(
                title="Código de verificación expirado",
                description=f"Para generar un nuevo código de verificación accede [aquí]({AUTH_URL})"
                            f", una vez iniciada sesión (no aparecerá ninguna web) copia el enlace "
                            f"y dale al botón de introducir código",
                color=0xFF00FF
            )
            await interaction.response.send_message(embed=embed, view=NoAccessTokenView())

    @app_commands.command(name="sendall")
    async def sendall(self, interaction: discord.Interaction) -> None:
        for member in self.bot.db.get_all_members():
            await send_store(interaction)

        await interaction.response.defer()


async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(Shop(bot))

#

the other command "tienda" is showing

shrewd apex
#

sync ur commands and hit ctrl + r if on discord desktop

thin raft
shrewd apex
#

when u sync the commands u get a list of returned commands which were synced is that command present in the list?

thin raft
#
class Bot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(intents=discord.Intents.all(), command_prefix="..")
        self.db = DB()

    async def setup_hook(self) -> None:
        await self.load_extension("cogs.shop")

        await self.tree.sync(guild=discord.Object(931192437949485116))
        print([c.name for c in self.tree.get_commands()])
#

the print shows tienda and sendall

shrewd apex
#

no the sync call returns a list of synced commands

thin raft
#

oh

#

not returning anything

shrewd apex
#

!d discord.app_commands.CommandTree.sync

Returns
The application’s commands that got synced.

Return type
List[AppCommand]
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...
thin raft
#

yeah

#

just checked it

shrewd apex
#

are u sure the guild id is correct and when bot was added it was added with application commands scope?

thin raft
#

it was added as admin

#

im confused about one registering but not the other one

shrewd apex
#

thats wierd but it's likely that after the first command sync even tienda probably didn't get re synced

#

do you get any errors?

woeful hill
#

You declare a global command but you sync guild

naive briar
#

Shouldn't be a problem, I don't think

thin raft
#

fuck it was that

timber dragon
#

Yeah that only syncs the commands for that specific server

warm kestrel
#

@calm vector can you mute/deafen/move/disconnect @ lemon in exemple?

#

i mean in vocals

viscid hornet
viscid hornet
fast osprey
viscid hornet
fast osprey
#

what it is they want

round knoll
#

hi, i cant seem to be able to give a simple role to a on_member_join event. am i missing something, i feel like it should be easy...

slate swan
#

currently missing the whole code

fast osprey
#

Code? And what's the goal of giving everyone a role?

round knoll
#
        @self.event
        async def on_member_join(member):
            print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------{member} has joined the server----------")

            # drifters role
            has_drifter_role = self.DRIFTERS_ROLE_ID in member.roles

            if not has_drifter_role:
                await member.add_roles(member.guild.get_role(self.DRIFTERS_ROLE_ID))
                print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------Added Drifters role to {member}----------")
young dagger
round knoll
# young dagger 1. Does the bot have permissions to manage roles? 2. Does it print anything?
  1. yes
  2. yes

the bot already manages roles and random stuff, its working fine for everything else. it throws an error

2025-03-08 16:20:13 ERROR    discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
  File "/home/zed/.local/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/home/zed/Projects/ZeddyBot/zeddybot.py", line 336, in on_member_join
    await member.add_roles(member.guild.get_role(self.DRIFTERS_ROLE_ID))
  File "/home/zed/.local/lib/python3.10/site-packages/discord/member.py", line 1051, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
#

it also prints that the user joined, with proper formatting and all

2025-03-08 16:20:13----------testy_test_mctest has joined the server----------
[<Role id=428788808754921472 name='@everyone'>]
False
1347960879500755066
timber dragon
#

it can't find the role in that server

young dagger
#

Does the role exist?

round knoll
#

i grabbed the role id from the developer option when you right click on the role in discord

timber dragon
#

make sure it's int

#

self.DRIFTERS_ROLE_ID in member.roles isn't valid either, member.roles is a list of Role objs. Use member.get_role(ROLEID).

also, you don't need to get the full Role obj just add it; use discord.Object(ROLEID)

round knoll
young dagger
round knoll
#

thanks @timber dragon and @young dagger

#

it's cause im loading all the stuff from a config.json .. it's a string inside of it, makes sense

young dagger
fast osprey
#

json is a pretty crap config format anyways compared to things like toml and yaml. It was designed for data exchange, not configuration

young dagger
round knoll
#

ill have to refactor at some point, but at least its working now. ill do a couple more tests just to make sure

unreal owl
#

What would be the best way to get the user_id out of a username?

blissful crane
unreal owl
#

I hope you get what I mean

blissful crane
#

there are a couple things to note here

  1. Ticket systems that use channels are not recommended, it's best to use private threads
  2. using names for something like this is not recommended, ids are better since they're unchangeable and unique
  3. Guild.get_member_named will take a name str and return a discord.Member if possible
sick birch
#

usernames in channel names is far more convenient, it's how @novel apex works

#

you can put the user ID in the channel topic though

stark ingot
#

IMO still use a small database, it prevents issues where the channel name/topic is changed

fast osprey
#

(and also don't use channels for this to begin with)

viscid hornet
unreal bay
#

.env file exists: True
TOKEN: None
OWNER_ID: None
Error: DISCORD_TOKEN environment variable not found.

unreal bay
viscid hornet
pale zenith
ember ibex
#

The on_message listener never seems to work for me. I have given my bot every single permission there is, made sure there are absolutely no errors, made sure that the cog is loaded and nothing else is interfering. NONE of the code executes in the on_message listener

class GeneralCommands(commands.Cog):
    def __init__(self, bot, config):
        self.bot = bot
        self.db = MainDatabase()
        self.config = config
        print("GeneralCommands Cog Initialized")


    @nextcord.slash_command(name="test_general", description="Hello")
    async def test_general(self, ctx):
        await ctx.send("The general cog is loaded.")

    @commands.Cog.listener()
    async def on_message(self, message: nextcord.Message):
        await self.bot.process_commands(message)
        print("Listener triggered!")
        if message.author.bot:
            return
        
        print(message.content)
#

The slash command works, but whenever I send messages, the program doesnt print anything

viscid hornet
#

also you don't need to process commands because it's a listener, not the main event handler

ember ibex
ember ibex
viscid hornet
#

wait fuck

viscid hornet
#

brain segfault catderp

ember ibex
#

Is there an example of working on_message listener functionallity? I tried making a bot a few months ago with a listener and it also didnt work then. I've tried every code snippet stack overflow has given

ember ibex
vapid parcel
#

Anyone know how see all members the bot can see? I wanna just len it, but i don't chunck the guilds on startup, meaning i can't just call self.bot.users is there another way?

ember ibex
naive briar
vapid parcel
naive briar
#

You could wait until the bot is fully ready before doing that

#

If it's for a presence, that'd work

viscid hornet
vapid parcel
ember ibex
#

That's why I'm writing here, because it is structured exactly the same as the existing code online

vapid parcel
#

I can't have my bot just sit rate limited for 10+ minutes

#

That's the main issue, that's why I don't load the chunks on startup

viscid hornet
naive briar
vapid parcel
#

Mb, I meant, we don't actually have prefix cmds

viscid hornet
vapid parcel
#

🤷‍♂️

#

/ works 🤷‍♂️

#

Prefix cmds are for the weak 🙏

naive briar
#

I missed them 😔

vapid parcel
#

They were alr

#

Hybrid were on top

#

Actually, fuck hybrid, I fucking hate those things, they were a mix of bs, if u got the prefix working, u would have to remember to make it work for slash too 😭

#

To much work

#
total_counts = [guild.approximate_member_count async for guild in self.bot.fetch_guilds(limit=None)]
total_users = sum(total_counts)

Well, this is my fix to my question, thanks to my glorious king @finite salmon

finite salmon
#

on god

vapid parcel
#

❤️

last cradle
#

how to go about making a command like this w/o api

fast osprey
#

What do you mean "without api"? And this screenshot doesn't really say anything about what this command actually does or what logic it uses

midnight oracle
#

I know it's possible, I just don't remember how. How was it to make a button copy to clipboard something?

naive briar
#

I'd guess make a URL button and redirect to a page that then adds the stuff to your clipboard

#

Don't know if it's possible any other way though

midnight oracle
#

I just read about it in StackOverflow

#

Thanks!

timber dragon
#

Link to post? 👀

young dagger
#

Can masked links in messages be detected without using regex?

fast osprey
#

Why do you not want to use the tool specifically designed for detecting patterns in text

fast osprey
#

Regex

#

Asking how you find specific patterns in text without regex is like asking how you eat soup without a spoon

young dagger
fast osprey
#

It does, and it uses regex

stark ingot
unreal shuttle
#

guys, is there a way to automatically send my robinhood trade positions to a discord channel?

#

for context, Robinhood is an investing platform that can also be used for daytrading

fast osprey
#

You can post whatever message you want to a webhook

#

how you create that message is entirely up to you

unreal shuttle
#

i mean, how can it be integrated into a python code?

fast osprey
#

Webhooks are just api endpoints with a specific payload. It's up to you to write the code that gets the info you need and crafts the message you want

#

Libraries like discord.py simplify sending to that webhook, but as far as it's concerned it's entirely on you the developer to figure out what message you want to send

viscid hornet
wanton current
#

Webhooks aren't bound to a bot

#

If you have the webook url you can always send messages to it

ember robin
#

My ephemeral isn't working, but there are zero errors.

#

I've also created a post if someone would like to help me out.

fast osprey
#

Are you deferring and then following up?

ember robin
fast osprey
#

What's your code?

viscid hornet
unkempt canyonBOT
#
Virtual environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
unreal bay
timber dragon
#

Nah

fast osprey
#

Might want to read #rules number 9

vernal folio
#

Anyone who wanted to help me building bots with me?

#

🙂

fast osprey
#

lol

#

Very smooth

quick gust
#

Just ask for help with whatever you need, here

slate swan
#

why i cant use voice message

#

because permissions

stark ingot
slate swan
#

aaaaand guilds/clans are now gone

stark ingot
#

To clarify my reaction above, dont care about the clans feature itself, it does not effect me. But the many of the people who used them in scummy ways... im glad wont be able to do that

viscid hornet
stark ingot
#

Abusing the fact that it was an experiment and only some people had access

viscid hornet
stark ingot
#

among other things yes

viscid hornet
#

@stark ingot how does externally setting a discord RPC work?

viscid hornet
#

hence externally setting

slate swan
#

You mean like set a presence from another app?

viscid hornet
#

pretty much yeah

#

set presence from code, specifically

slate swan
#

IPC connection

viscid hornet
#

wtf man this channel has been quiet for 10 hours why is there slowmode

viscid hornet
slate swan
#

then it's just about sending the right commands

slate swan
#

then send data to that connection, the data is the set presence command with the information

viscid hornet
#

also for websockets, what's the difference between that and a webserver

#

and what modules do you use for setting up websockets as opposed to a webserver

slate swan
slate swan
slate swan
viscid hornet
viscid hornet
slate swan
viscid hornet
slate swan
slate swan
#

Instead of, for example, doing a request to a REST endpoint every 5 seconds to have the updated information

viscid hornet
#

i dont get any of this

#

can i at least see some example code?

slate swan
#

ehm wait

slate swan
#

most of the code is not relevant, but the xlient/utils part to get the path and connect to it should at least get the rough idea of how it works

viscid hornet
#

(with websocket-client)

from websocket import create_connection

ws = create_connection(r"\\.\pipe\discord-ipc-0")
ValueError: url is invalid

am i just JoeBonkers

slate swan
#

yeah because it's not the same

#

a socket connection to an ipc pipe isn't the same as connecting to and using a websocket

viscid hornet
#

yeah ima just use pypresence

#

fuck this

slate swan
#

you just need the stdlib with socket module

slate swan
timber dragon
#

axo isn't slowing loosing it anymore, she lost it.

viscid hornet
viscid hornet
#

it's cuz i dont know the structure of it so i have no fucking clue what goes where

slate swan
viscid hornet
slate swan
#

then looking at the presence code is best

turbid condor
#

can anybody tell me how to lock a thread using bot command i'm using dpy

#

I only found delete in the documentation

turbid condor
#

ahh so it's in threads

#

thanks I was checking Forums

timber dragon
#

Forums hold threads lol

turbid condor
#

yeah that got me confused

#

since there are threads similar to a text channel too

woeful hill
#

a post in forum channel is a thread

slate swan
#

and a thread is just a channel type

tawny junco
vapid parcel
tawny junco
vapid parcel
#

hybrid cmds were different than regular slash cmds

#

and certain arguments you had to treat differently

tawny junco
#

It's been a while since I used regular slash commands. But how different are the arguments? (not arguing btw just need a refresher)

vapid parcel
#

Making it in my opinion, slash cmds betters.

tawny junco
# vapid parcel First off, slash cmds require you to have typehints in arguments, and Hybrid doe...
@commands.hybrid_command(aliases=["j", "J"], description="Searches for Japanese words")
    async def jisho(self, ctx: commands.context, *, arg: str) -> None:
        page_view = PageView(ctx=ctx, arg=arg, data=self.word_search(arg))
        await page_view.send()

This is my hybrid_command that was originally a prefix command. What did you mean by keyword-only markers? I really forgot how app_commands work (this is what you call slash cmds right?)

vapid parcel
#

*, arg: str

* is the keyword only marker.

#

you would never need that in an actual slash cmd

tawny junco
#

wait hold up. gimme a sec to check something

naive briar
#

What does it do to prefix commands I wonder

tawny junco
#

I just ran the command without it

tawny junco
vapid parcel
#

not the slash cmd

tawny junco
#

Normally, if you don't use the *, args syntax then what happens is, for every space you enter will be passed as an argument. For example

@bot.command()
async def calculate(num1, op, num2):
    ...

# on discord: !calculate 4 + 6

this is equivalent to saying calculate("4", "+", "6"). So it's just spaced arugments. If you add another space and do !calculate 4 + 4 + 6 then you'll get the parameter error (not enough parameters blah blah)
but if you could just do **kwargs to filter out extra arguments. But there's a catch. It might even be a bug idfk but you can't do it for large amounts of text for whatever reason and you also don't get quotations from text. what the *, arg does is treat every space as part of the argument including all special charactors and quotations. It's NOT NEEDED for prefix commands. It just depends on what you wanna do. I originally used it for a google translate api because having all you text in one string with all quotation is pretty handy for translating

#

Idk why it took me so long to type that @vapid parcel@naive briar

vapid parcel
#

Yes, but most arguments will need *, not saying you NEED it in every cmd, but if you are making a cmd with a default value like reason= or another thing, you will be using *, and I had a lot of cmds like that, and thats why I just don't like hybrid cmds. I understand what you are saying, but a majority of hybrid cmds will be using *.

tawny junco
#

I thought the argument here was it is absolutely required to use the *