#discord-bots

1 messages · Page 387 of 1

simple surge
fast osprey
#

If this is user message content, are you implementing the privacy protections you have agreed to in the TOS? Unlikely you have a robust system for looking through these files if someone invokes their right to be forgotten

simple surge
fast osprey
#

That does not waive you of the responsibilities you have agreed to

#

Alternatively you could just let people use discord and not try to handle this yourself

simple surge
fast osprey
#

It is. You are interfering with privacy features, namely people's ability to request their messages be removed

#

just leave the messages in discord. People can read them there

simple surge
fast osprey
#

And it can be logged. In discord

#

what mechanism do you have for a user to request you for their data to be deleted? How are you going to do so? This is not discord asking you, you have agreed to grant this directly to users

#

Is this data encrypted at rest?

simple surge
#

It'd be only me and the person who created the ticket; who have permission to view the transcript?

fast osprey
#

that doesn't impact the responsibilities you have agreed to.

uneven wadi
#

Don't most or popular tickets bots have transcript system though?

fast osprey
#

Someone doing something doesn't mean it is okay or legal to do

uneven wadi
#

What I mean is

#

They're verified bots

fast osprey
#

That doesn't matter

uneven wadi
#

If what you're saying isn't legal

#

Why are they still there

fast osprey
#

Someone breaking a law doesn't mean you get to

uneven wadi
#

Like why the bot ain't banned or something

fast osprey
#

The TOS are clearly outlined. And this server's rules say you are not allowed to ask for help in breaking TOS. Someone else breaking the TOS and getting away with it don't factor into either of those shrug

#

At the end of the day, you can view "tickets" just fine in discord. If you want to pull those things out of discord, you have a whole slew of things you are responsible for. It isn't worth the headache, you can just use what already exists and users' privacy rights will be automatically maintained. Given you don't know what those responsibilities even are, you certainly have not implemented them. It's up to you if it's worth it, but that's not something you can just skip and worry about later

simple surge
#

Homie you are just yapping 😭

young dagger
#

@simple surge Don't use the R word

#

Just say stupid or something else

simple surge
fast osprey
#

Again. People doing something is irrelevant

#

Unless you are implementing user privacy protections you have agreed to, which you have made clear you are not, this is against TOS. Other people also violating TOS does not change that

pseudo sedge
#

whats the issue

fast osprey
#

That's js?

pseudo sedge
#

yes

fast osprey
#

This is the python server 😂

pseudo sedge
#

how do i know if is it js or no im just saying thats js

fast osprey
#

node index.js

pseudo sedge
stark ingot
#

You should probably learn the basics of programming before trying to create a bot

fast osprey
#

There's a discord.js server (assuming that's what you're using) that will give you better help

visual yarrow
#

Hi. We don't appreciate the use of ableist language here, or personal attacks. Please don't do that again. Thanks.

simple surge
mild token
#

You can just use thread bud which will save u alot of headache all will be saved in your channel as well ,u can look into private threads which is more efficient

#

I personally just use them as ticket and with ticket(threads) i don't even have to save anything in my db all are saved in discord itself which saves my db resources as well

uneven wadi
#

Guys, will you guys help program a bot?

ionic cave
#

I need help

#

import discord
from discord.ext import commands

intents = discord.Intents.default()
bot = commands.Bot(command_prefix='=', intents=intents)

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

@bot.command(name='H')
async def hello(ctx):
await ctx.send(f'Hi!')

This ain't wokring

#

working

fast osprey
#

What is happening, and what do you want to happen?

stark ingot
ionic cave
#

I got it to work,

fast osprey
#

(That should also result in a library log saying as much)

mild token
#

If I want to select emoji with context menu does discord.Emoji will work as method parameter of context menu ?

fast osprey
#

context menus only accept messages or users

mild token
#

Oh so I need to check the message type then tnx for the info

minor geyser
#

hey so, i have this py for server in client.guilds: print(server.name) and i want to make it so that it assigns the servers name to a value so that i can use a function specifically for that server (like getting information about the guild) from the command prompt

#

i just cant comprehend how to do that right now,, yert

fast osprey
#

What does "a value" mean?

#

Servers already have a unique ID

late remnant
#

hi guys

#

does anyone know how i can unittest my discord bot commands and events

scarlet tiger
sick birch
#

this is how we test @unkempt canyon

late remnant
scarlet tiger
sick birch
#

it's generally a good idea to have multiple methods of testing yeah

scarlet tiger
#

Yeah

sick birch
#

it may be valuable to have a mix of unit tests and E2E tests for instance

late remnant
stark ingot
#

On discord bots can not run app commands so you would have to make fake data that you could feed the command callback

late remnant
#

yeah thats what im currently doing

pallid sonnet
#

Does anybody know of of any discord bots like this for any game?

dapper cobalt
#

!docs discord.ext.commands.Bot.get_guild

unkempt canyonBOT
minor geyser
dapper cobalt
minor geyser
#

something where it writes ”1”: “servername here” in a json file on every start and read/writes ig

dapper cobalt
minor geyser
#

Yeah makes sense, I just meant that in general it could work lol

dapper cobalt
#

also I don't think you'd memorize the order of your bot's servers

uneven wadi
#

Hey, how can I make a bot run with a server? Like hosting you know, any free plans available?

dapper cobalt
#

however, if you want to get the server by name you could loop through the bot's guilds and use an if statement inside the loop to check whether it's the server you're looking for and if so return its data

#

it'd be something like this

names = ["zika", "seif"]

for name in names:
     if name == "zika": 
           print("hello world")
minor geyser
#

hm, i reckon I could do

num = 0
for server in client.guilds:
    print(f”server {num}: “+client.guilds[int(num)])
    num = int(num) + 1
serverchoice(“Server to operate on:”)
do.stuff(client.guilds[int(serverchoice)])```
vocal laurel
#

!d discord.ext.commands.Bot.get_guild

unkempt canyonBOT
minor geyser
#

Sorry aha I was typing that on mobile 😅

vocal laurel
#

you may just use that to get it

minor geyser
vocal laurel
#

oh nvm, sorry

minor geyser
# vocal laurel oh nvm, sorry

All good, I’m a bit bad at putting my thoughts into words and asking for help in general so if there’s a misunderstanding it’s 100% my fault lol

vocal laurel
#

Nope, I just didn't read the whole thing so that is mb

vocal laurel
dapper cobalt
vocal laurel
#

you could just get_guild if you have the id

minor geyser
vocal laurel
#

Like if you put the name of the server, you could just use the example given above

#

using a for loop

minor geyser
vocal laurel
#

server 1 or server 2?

#

hm

#

Well you could store the server number in a data base for example

Server number | Server ID

1 | 42394839438294832

and basically you fetch the server ID based on the server number that you searched for

#

you would also have to account for when the bot leaves a server, what number that should be etc

minor geyser
#

well yeah I just don’t need to store them lol i just suggested json as opposed to typing out or copy and pasting the ID

minor geyser
#

If I stored IDs and stuff it would bloat overtime and eventually get too big, all I wanna do is be able to do is fetch some info by typing a number, so this should work

#

Thanks! :3

mild token
#

how can i remove someone from thread? when i do remove user it doesnt fully remove the member from the thread rather on its name slash is there

#

i want that person to completely remove from thread

vocal laurel
#

This is so you don't have to create a database

#

guilds is to create a list of all guild ideas, then selected_guilds is to get the guild you want from that list and guild is to fetch that guild based on the selected_guild id

vocal laurel
unkempt canyonBOT
#

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

Removes a user from this thread.

You must have [`manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads) or be the creator of the thread to remove a user.
mild token
#

but there is slash coming on that name

#

when i remove them

vocal laurel
#

Do you mind sending a screenshot?

mild token
#

see the person

#

he is not in thread

#

thats why slash is on its name

#

dont know why this happening

vocal laurel
#

Can I see your code please?

mild token
#
            if check_clan_player.clan:

                clan_data = await self.bot.db.fetch_clan(
                    clan_tag=check_clan_player.clan.tag
                )
                if clan_data:
                    mem_channel = await interaction.guild.fetch_channel(
                        clan_data["channel_id"]
                    )
                    stat_channel = await interaction.guild.fetch_channel(
                        clan_data["clan_stat_thread_id"]
                    )
                    clan_chat_channel = await interaction.guild.fetch_channel(
                        clan_data["clan_chat_thread_id"]
                    )
                    if user in mem_channel.members:
                        await mem_channel.set_permissions(
                            target=user,
                            overwrite=None,
                            reason=f"{user} have been removed from {mem_channel.name} channel. ",
                        )
                    if user in stat_channel.members:
                        await stat_channel.remove_user(user.id)
                    if user in clan_chat_channel.members:
                        await clan_chat_channel.remove_user(user.id)

            player_leader_role = discord.utils.get(
                interaction.guild.roles, id=RoleIds.LEADER
            )
            if player_leader_role in user.roles:
                embed.add_field(
                    name="Position role unlinked",
                    value=player_leader_role.mention,
                )
                await user.remove_roles(
                    player_leader_role,
                    reason=f"remove {str(check_clan_player.role)} from {user.display_name} which is of {check_clan_player.clan.name}({check_clan_player.clan.tag})",
                )

            await interaction.client.get_channel(Logs.PLAYER_LOG).send(embed=embed)

mainly i am doing on this part removing the person

#

its not very optimised but it works

mild token
vocal laurel
mild token
mild token
#

oki : (

vocal laurel
#

the code doesnt seem like the problem

mild token
#

i checked docs thrice

#

but this slash thing persisted

#

hope it fixes on its own

ivory remnant
#

is it possible to make commands for user installed bots in py? cause i made a command which works on my server but doesnt show in dms

#

and every example i have managed to find is in js

golden portal
unkempt canyonBOT
#
NEGATORY.

No documentation found for the requested symbol.

vocal laurel
#

!d discord.app_commands.allowed_installs

unkempt canyonBOT
#

@discord.app_commands.allowed_installs(guilds=..., users=...)```
A decorator that indicates this command should be installed in certain contexts. Valid contexts are guilds and users.

This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.

New in version 2\.4\.

Examples...
vocal laurel
#

^

uneven wadi
#

Hello, I want to create a bot that is similar to @unkempt canyon

#

Specifically made for a certain server i own

slate swan
#

Good luck and enjoy coding it

uneven wadi
#

i know a lil py

golden portal
#

couldn't you fork the bot and run your own instance?

sick birch
uneven wadi
uneven wadi
#

!rule 3

unkempt canyonBOT
#

3. Respect staff members and listen to their instructions.

uneven wadi
#

this one

sick birch
uneven wadi
#

how to do it

sick birch
#

!source rule

unkempt canyonBOT
#
Command: rules

Provides a link to all rules or, if specified, displays specific rule(s).

Source Code
uneven wadi
#

omg thanks!

mint pecan
#

is commands.bot_has_permissions and app_commands.checks.bot_has_permissions the same?

fast osprey
#

No

warm radish
#

@small rose

#

@crude summit

#

@misty yoke

uneven wadi
#

Hello

#

why i cant disable public bot

vocal plover
#

If you're not able to disable it you should contact Discord support, that shouldn't be happening and there's not much anyone here can do about it

slate swan
slate swan
uneven wadi
#

thanks!

slate swan
#

👍

vocal plover
#

I stand corrected, I need to un-rusty myself with the current status of bot dev apparently

uneven wadi
#

Guys.

#

Do i need __init__.py for my bot

#

have no idea what it does

#

but seen it @unkempt canyon in repo

vocal plover
#

That really depends on the context, __init__.py is essentially how you create a module, so if you had a folder called abc with an __init__.py in it, and that file contained - for example - a setup() function for a Cog, you could import that folder as simply abc rather than abc.something if the file was called something.py. It basically lets you organise your code if you need multiple files grouped together. Python Discord's bot is a large bot with a ton of code so that sort of structure is necessary to keep track of it, but if you have a small bot you can get away without those files for now (though familiarising yourself with them and what they do is great for your learning journey, and I'd highly recommnd looking into the structure of Python projects more)

uneven wadi
uneven wadi
#

So i dont need init for now ig

vocal plover
#

Just think of a couple of things to start with, a couple features you know you want, and go from there. Rushing in with a ton of stuff will burn you out quickly - try and pick the things you're really excited about as the features you make first

fast osprey
#

IMO there are two distinct things here

  • if you're trying to learn the library, hello world + very simple api interactions. Have a hypothesis for what you want to learn
  • if you're trying to make something useful, actually observe a problem and design a novel solution to it. Rewriting the 10 features every bot has just makes you 97538th in line
vocal plover
uneven wadi
#

not doing anything rn but should i create commands with prefix first and convert them to slash?

vocal plover
#

If I were starting out now I'd ignore prefix commands, they're not liked by Discord and are gradually losing support in favour of slash commands. Unless you find something that you really can't find a way to make with interactions-based stuff (i.e. slash commands, buttons, menus, etc.) I wouldn't bother touching them

uneven wadi
#

noted

ionic cave
#

Give me some i can code with python on my discord bot, can't be to hard.

Replay if you got some,.

fast osprey
uneven wadi
#

😂

ionic cave
#

.

#

Real funny

ivory remnant
#

could someone give me an example on how to use userinstalled bots in discord.py? ive been trying for hours now and it works in my server but doesnt show in dms

viscid hornet
#

this sets where you can have the slash command: ```py
@app_commands.allowed_installs(guilds = ..., users = ...)


and this sets where you can use the slash command: ```py
@app_commands.allowed_contexts(guilds = ..., dms = ..., private_messages = ...)
#

dms is messages with the bot, private_messages is messages with other users

ivory remnant
#

nevermind i figured it out

#

tysm

viscid hornet
ionic cave
#

How do i make an embed?

fast osprey
#

Make a discord.Embed object -> call methods on it to set fields and whatever you want -> send it on a message with the embed= arg

thorny hull
#

Hope this is the appropriate channel for this. I have a discord.py bot that posts a message with some reactions. Users react to this message to have roles assigned and removed. It all works great but breaks whenever the bot restarts. Tried using a few different datasources to store the info of the reactions, channel_id and message_id and they all seem to work ito storing and retrieving but whenever the bot restarts, the functionality of the "Reaction Message" is lost. I have a workaround but it's less than ideal. It involves recreating the reaction message whenever the bot starts.

Any ideas? Is there some limitation in the API to prevent this functionality or perhaps a setting or two I missed in the Developer portal?

scarlet tiger
fast osprey
#

Or consider using the built in onboarding channels & roles dialogue, then you don't need a bot running at all

thorny hull
thorny hull
fast osprey
#

You can do that with that menu

#

I have servers that do this often

slim bloom
#

@fast osprey

#
import os, shutil, aiohttp, aiosqlite
from discord.ext import commands, tasks

class Tasks(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    @commands.Cog.listener()
    async def on_ready(self) -> None:
        self.backup_database.start()
        print(f'Cog {self.__class__.__name__} is ready')

    @tasks.loop(hours=168)
    async def backup_database(self):
        if os.path.exists('src/database/backup.db'):
            os.remove('src/database/backup.db')

        shutil.copy2('src/database/bot.db', 'src/database/backup.db')

async def setup(bot):
    await bot.add_cog(Tasks(bot))```
## How could I improve it or what aspects were wrong?
fast osprey
#

You really should not be using on_ready to drive functionality. This happens repeatedly and randomly

#

There's also really not much of a point in having a cog that has a single thing in it, it's just unnecessary boilerplate imo

slim bloom
fast osprey
#

You can just make a normal ass task and start it in the setup

#

don't need a cog or on_ready at all

#
@tasks.loop()
async def whatever():
  ...

async def setup(bot):
  whatever.start()
slim bloom
fast osprey
#

or in an extension, wherever you want

slim bloom
fast osprey
#

Entirely different concepts, the docs have pages on both

vocal laurel
#

Do you still need it? @slim bloom

slim bloom
vocal laurel
# slim bloom yeah

I can't find docs for it but afaik, extensions are files that you load into your main file and cogs are groups of command put into an extention that you then load into your main file

slim bloom
golden portal
#

if its within a cog just start it in cog_load

#

!d discord.ext.commands.Cog.cog_load

unkempt canyonBOT
#

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

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.

New in version 2\.0\.
thorny hull
thorny hull
mint pecan
#

how can i make my bot work like this that i can specify the argument in a prefix command?
!ban user=@someone reason="rule 1"

mint pecan
golden portal
#

in the class def of the flag class, the doc shows an example of it

mint pecan
# golden portal in the class def of the flag class, the doc shows an example of it

im getting
discord.ext.commands.errors.MissingFlagArgument: Flag 'user' does not have an argument
this was my code

class BanFlags(commands.FlagConverter):

    user: discord.User | discord.Member
    reason: Optional[str] = None

@commands.command()
async def ban(ctx: commands.Context, flags: BanFlags):
    await ctx.reply(flags.user.mention)
mint pecan
#

ohhh

#

i forgot that

slate swan
#

!intents

uneven wadi
#

lol

stoic tusk
#

anybody knows how to code the new Group Chat update for bots?

feral wren
#

guys

#

what 'async def 'means?

fast osprey
#

Defines an async function

stark ingot
silent folio
#

Can someone tell me what a discord bot is

wanton current
#

a bot user that uses code to interface with the discord api

jagged crown
#

How to fix this it won't response just trying to make a simple Bot

#

I'm just a beginner

sick birch
unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

sick birch
#

couple things:

  1. post your code as text next time, images of a phone screen are hard to read
  2. reset your token
vocal laurel
#

I am having a problem with my help command. With the code sent below, the bot sends an embed but creates 2 fields within the embeds for the commands (basically creating it for each category/cog). However I want it to send all the commands in 1 field regardless if it has a category or not, how would I go about doing this?

  async def send_bot_help(self, mapping):
    em = discord.Embed(title = "Help Command")
    em.color = discord.Color.from_rgb(93, 211, 251)
    for cog, commands in mapping.items():
      filtered = await self.filter_commands(commands, sort=True)
      command_signatures = [self.get_command_signature(c) for c in filtered]
      if command_signatures:

        em.add_field(name="Commands", value="\n".join(command_signatures), inline=False)

    await self.get_destination().send(embed=em)
golden portal
#

just this? ```py
all_commands = []
for ... in mapping.items():
...
all_commands.extend(command_signatures)
all_sig = '\n'.join(all_commands)

vocal laurel
#

it works, tysm

drifting arrow
#

What's the discordpy thing to have loops etc?

drifting arrow
#

Is there a discordpy thing to make a task run at a specific time every week? say monday 12pm?

shrewd apex
#

yes

#

u can enter the time but for checking the day u can use the tzinfo and something like calendar module to check if it's that particular day in like before_loop

silent folio
#

What is the main language and libraries for discord bot???

hollow osprey
silent folio
#

Ok thanks

feral wren
#

guys

#

i need a funcition who let only to users who has 'admin' role to use mod commands like 'ban',mute ecc. with my bot

quasi frigate
fast osprey
#

You should really not be overriding mod actions that already exist in the client, you are actively reducing their security.

If you want to restrict app commands, you should use the default_permissions decorator rather than a local check

vocal laurel
# feral wren i need a funcition who let only to users who has 'admin' role to use mod command...

if you are looking for permissions, then use the deco suggested above, however if you are looking for roles, then you would use

@app_commands.checks.has_role() #checking for 1 role
@app_commands.checks.has_any_role() #checking for multiple roles

^ for app commands (aka slash commands)

@commands.has_role() #checking for 1 role
@commands.has_any_role() #checking for multiple roles

^ prefix/text commands

fast osprey
#

App command role limiting should be done from the integrations menu, not a local check

feral wren
#

@bot.tree.command(name="add_role", description="add a role to a member")
@commands.has_role('Mod')
@app_commands.describe(member="The member to ban", role = "the role to add")
async def addrole(interaction:discord.Interaction,member: discord.Member, role: discord.Role):
    emb = discord.Embed(title='addrole',description=f'the role {role} as been added to {member}')
    await member.add_roles(role)
    await interaction.response.send_message(embed=emb)

#

this is the command add_role

#

but everyone in my server is able to use it

#

what's wrong in this script?

quasi frigate
#

youre using the text command decorator instead of the slash command decorator

#

it should be @app_commands.checks.has_role('Mod') instead of @commands.has_role('Mod')

fast osprey
#

And there are several reasons why you should use the integrations menu instead

#

This code also lets people grant others roles they shouldn't be allowed to. You can already grant roles from the client

slate swan
#

hi guys, just wondering why instead of image, the code is giving me base64 text

sick birch
#

sometimes images are b64 encoded

slate swan
#
@bot.command()
async def imagine(ctx):
    
    api = Text2ImageAPI('https://api-key.fusionbrain.ai/', '7D62CC5E605', '974CDBCAA8EE6910F74')

    model_id = api.get_model()
    uuid = api.generate("Sun in sky", model_id)
    images = api.check_generation(uuid)
    print(images)

heres the code

harsh orbit
#

there is some bots that has a premiuem subscreption
and every premuim subscriber has its own bot with name and photo changable
the bot has same commands of the original bot but with more commands and featuers
how is that possible?

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: string indices must be integers
no wonder why im getting this error

fast osprey
young dagger
#

Where exactly is the check for invite links? Because I cannot find it

young dagger
#

Can you resume the interaction after restarting the bot?

harsh orbit
#

could you give me example for how to run that automaticcly pls?

zinc gust
#

that everyone can puts in their servers

#

and they could get more commands

#

by subscribing

#

?

fast osprey
#

You don't

#

you can't make bots automatically

harsh orbit
harsh orbit
fast osprey
#

There is not an automatic way to make bots, period

#

not without violating tos

#

Sure you could make a bunch of them in bulk, but there's still a limit. There's no functional need to do this. People can live without putting their dumb anime profile pic on a bot, just use the one bot

young dagger
#

Is it possible for the delete_message_seconds parameter to not selectively delete messages from a specific channel upon a ban?

#

There is nothing about excluding a channel

fast osprey
#

discord doesn't provide that afaik

young dagger
#

They should

#

Looping through channels is pain

fast osprey
#

What are you trying to accomplish?

young dagger
viscid hornet
young dagger
#

It will delete all messages

exotic hazel
fast osprey
#

2.4.0

That is the example published with 2.4.0, which is currently the most recent stable version

exotic hazel
#

I see, thank you

fast osprey
#

In general, it's not too terribly unlikely for some core things to not change at all within a major version (2.x.x). Any additions will be backwards compatible anywho, so in theory any example written in 2.0.0 will work for any 2.x.x

jaunty cape
#

First of all, you leaked your token

#

Second of all, you’re not passing any arguments

#

Third of all, are you using the correct prefix?

#

Fourth of all, you don’t need to set a name for a command if it’s going to be the same as your function name anyways

#

Fifth of all, is your command tree set up properly?

forest surge
#

bro I want to familiarize with this who wants to make a project or just do something

fast osprey
#

Best way to convince people that you're serious and good to work with is to put forth the effort to learn on your own and have examples of your work that you can show IMO

stark ingot
#

Almost all projects start as a solo dev that makes the base of the code than showcase their project in the relevant community. Sometimes people will see it than want to help.

#

It also helps if you have a unique idea, as more people will be interested

neon ocean
slate swan
#

so the api key is longer than short one

livid hare
#

anyone can help me about automation script already ended working but something wrong cuz one script won't working but no error i can't understand why don't working

#

idk where to post

stark ingot
#

Is it about discord bots?

livid hare
#

anyone can give me proxy scraper?

young dagger
#

I'm working on a new verification system for my Discord server using captcha

slate swan
#

can u edit a webhook in py

hard kite
#

Uhm how to make command invisible for user that has no specific role?

fast osprey
#

For app commands, the integrations menu on the guild

young dagger
#

Why do I sometimes get interaction failed when clicking a button, but it works again after restarting Discord?

#

I don't need to restart the bot, just my own Discord client

vocal laurel
#

You have to sometimes restart your discord client to get the latest changes from your bot

vocal laurel
#

sometimes it doesn't instantly refresh on your discord client

young dagger
young dagger
#

My final server captcha verification

stark ingot
young dagger
#

@stark ingot Do you have any solution?

stark ingot
#

No, I have no idea why a button gets fixed when you restart discord

#

I assume you mean there is red text on discord that says interaction failed?

young dagger
#

Maybe I should use something else instead of timeout=None on the view?

stark ingot
#

Well if the view needs to be persistent than you have to use timeout=None

drifting arrow
#

I need some fresh set of eyes on this..
Why is that line grayed out? it should work..

#

🤔

#

What'd I do wrong chat?

#

Definitely not an indentation issue..

hearty basalt
#

i think you meant "if not steamid or not steamurl"

#

right now if a steamurl is given, it satisfies the first if and will send the "please enter id or url" msg

scarlet tiger
drifting arrow
drifting arrow
#

I made a mistake with my code.

drifting arrow
#

Here's the full corrected finished code now.

    @app_commands.command(name="connect", description="Connects your steam account to your discord account to claim rewards")
    @guild_only()
    async def connect(self, interaction:Interaction, steamid:str=None, steamurl:str=None):
        await interaction.response.defer(ephemeral=self.config['ephemeral_response'])

        if not steamid and not steamurl:
            await interaction.followup.send("Please enter either a steam ID or steam URL.", ephemeral=True)
            return

        if steamurl:
            steamid = await self.functions.steam_profile_using_url(url=steamurl)

        response = await self.functions.update_discordid(steamid=steamid, discordid=interaction.user.id)

        if response:
            await interaction.followup.send("Successfully linked your discord account to the steamid!", ephemeral=self.config['ephemeral_responses'])
        else:
           await interaction.followup.send("That steamid is already linked to a discordid. Consult the staff to resolve this issue.", ephemeral=self.config['ephemeral_responses']) 

``` works no issues
hearty basalt
#

yay

drifting arrow
#

Wait. it should be and not steam url

#

@scarlet tiger - You can set a paramater to "None" or a preset value and it becomes optional. If you don't define a value it becomes mandatory.

#

You can also do things like set a parameter to discord.file or i believe it's discord.member or int or a boolean

#

I cant remember all of them but that's some of them

#

oh and discord.channel

#

by setting it to these specific paramaters you remove the possibility for your members to mess up the command, for example setting it to discord.channel creates a menu where the user can find the desired channel. similarly for discord.member

scarlet tiger
drifting arrow
#

I always opt to create everything in such a way that the end user, no matter how dumb or intellect they are, cannot mess it up.

#

I hold their hand as much as possible.

#

;-; Great new issue, error. Finally decided to run my code..

AttributeError: module 'discord.ext' has no attribute 'tasks'

My imports:

import json
from datetime import datetime, timedelta

from discord.ext.commands import Bot, Cog
import discord.ext

from discord import app_commands
from discord.interactions import Interaction
from discord.app_commands import guild_only

from plugins.seeders.supportfiles.embeds import seeders_embeds

from plugins.seeders.supportfiles.functions import seeders_functions

My code:

    @discord.ext.tasks.loop(minutes=1)
    async def check_seeders(self):
        reset_points = await self.check_start_of_week() #Checks if it's the start of the week.
        #The rest is not needed
#

🤔 is it an import issue? i think it is

#

Alright. it was. had to do from discord.ext import tasks

drifting arrow
#

How do I send multiple embeds? I tried await interaction.followup.send(embeds=[steam_embed,base_embed], view=the_buttons) but it breaks lol

fast osprey
#

What does "it breaks" mean?

drifting arrow
#
discord.app_commands.errors.CommandInvokeError: Command 'stats' raised an exception: AttributeError: 'NoneType' object has no attribute 'to_dict'

C:\Users\decla\OneDrive\Desktop\discordbots\developerbot>
#
Traceback (most recent call last):
  File "C:\Users\decla\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\decla\OneDrive\Desktop\discordbots\developerbot\plugins\stats\stats.py", line 50, in stats
    await interaction.followup.send(embeds=[steam_embed,base_embed], view=the_buttons)
  File "C:\Users\decla\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\webhook\async_.py", line 1785, in send
    with handle_message_parameters(
         ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\decla\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\http.py", line 172, in handle_message_parameters
    payload['embeds'] = [e.to_dict() for e in embeds]
fast osprey
#

One of those things is None

drifting arrow
#

my embed variables? impossible. if it's getting to the point where it's sending the messed it means the embeds generated as intended

#

nope. nevermind. was possible. lol

#

i forgot to return 1 of the embeds xD

#

Ty @fast osprey

young dagger
#

What is a good way to clean old entries in a dictionary when users interact with buttons?

#

Do it in a background task, cleanup in existing code or use something like caching library?

fast osprey
#

That's pretty vague, as is it's not clear how these buttons relate to this dictionary

fast osprey
#

What's the problem you're trying to solve?

young dagger
#

Clean old entries from the dictionary

stark ingot
#

With only 10min you might be able to get away with an asyncio sleep

fast osprey
#

Why?

stark ingot
#

Because that is the point of a cool down?

young dagger
#

Because the list is going to grow over time

#

And there is no need to keep track of these users

stark ingot
#

You could also start an ext.task for 10 min and only runs once but that might be unnecessary

fast osprey
#

Do you have reason to believe that it will grow enough to matter?

#

This really seems like optimizing before you actually have a problem

#

This is on the order of a handful of bytes

#

If you're already using the members intent, for example, that's already orders of magnitude more memory imprint

young dagger
#

Anyway, what would be the best solution for implementing some kind of cleanup in this case?

stark ingot
#

You could make a task run every 30min to an hour that loops through the dict and removes old entries

hushed galleon
unkempt canyonBOT
#

discord/ext/commands/cooldowns.py lines 119 to 126

def _verify_cache_integrity(self, current: Optional[float] = None) -> None:
    # we want to delete all cache objects that haven't been used
    # in a cooldown window. e.g. if we have a  command that has a
    # cooldown of 60s and it has not been used in 60s then that key should be deleted
    current = current or time.time()
    dead_keys = [k for k, v in self._cache.items() if current > v._last + v.per]
    for k in dead_keys:
        del self._cache[k]```
young dagger
young dagger
stark ingot
#

Yeah, whatever time interval makes sense

#

I just would not do any less than 15 min

hushed galleon
young dagger
stark ingot
#

If your cool down is 10 min it does not make much sense to check more often. And just a 5 min buffer. Not a fact but just my intuition that says you shouldn't :)

young dagger
#

Or I could run a task periodically to handle it

young dagger
young dagger
fast osprey
#

You can't make a good assessment on caching strategies when you don't even know how you're scaling. You're just assuming this will be a problem without proving it

#

you can't solve the problem until you quantify it, and I can guarantee from here that it's not a problem to begin with

young dagger
#

I'm interested in why you see cleaning up old entries as an issue

fast osprey
#

The same reason why crawling through your code base and minimizing every variable name is an issue. This doesn't matter in the grand scheme of things, and if you can't quantify it you're just picking random things to optimize

#

You cannot make an informed decision without information. If you don't know what is taking up memory and how much memory it's taking up, this is just guess work looking at code and theorizing it's something that needs fixing without having a way of proving that it got fixed. If your optimizations are not rooted in empirical evidence and just whatever you happen to notice, your code and your sanity are going to suffer.

sacred sand
midnight oracle
sacred sand
#

in terminal?

midnight oracle
sacred sand
midnight oracle
#

Indeed

sacred sand
#

okay ty

midnight oracle
#

:)

sacred sand
#

how do i put it on path?

sacred sand
midnight oracle
#

You could do it manually or just uninstall Python and install it again by clicking on the "Add to PATH" option in the installer, and it will do it for you.

sacred sand
midnight oracle
#

If you want to do it manually, go here.

sacred sand
#

ok ty

fast osprey
#

You need to select the py launcher option when installing python

zinc gust
#

and on the first "screen"

#

like the first thing that appears

#

there should be "add to path"

zinc gust
sacred sand
zinc gust
sacred sand
#

done

zinc gust
sacred sand
#

alr thanks

zinc gust
#

btw anyone got a way to lock an entire server with multiple role ?

#

like i mean when i lock a server i can only unallow a role to send messages

#

while there are other roles like helpers staff etc that i need to unallow aswell

#

but im getting rate limited because of the amount of role

sacred sand
zinc gust
fast osprey
#

Allows supercede denies. Just deny send message on @everyone and allow on the roles you want

sacred sand
#

Is this still valid?

sacred sand
#

it says its not valid..

#

fixed

sacred sand
#

why are there so many errors?

#

😭

scarlet tiger
sacred sand
#

It didnt really tell me to do much so

scarlet tiger
sacred sand
scarlet tiger
#

Ok pithink

sacred sand
scarlet tiger
sacred sand
scarlet tiger
sacred sand
scarlet tiger
sacred sand
#

yeh

scarlet tiger
#

Make sure to open the folder where the bot is

sacred sand
#

you mean the bot code?

scarlet tiger
#

It's not code, the error says that the file directory is not correct

sacred sand
#

i don't understand

scarlet tiger
#

Can you send me a screenshot of your VSC?

sacred sand
scarlet tiger
#

I want to see the files tab

sacred sand
#

this part?

scarlet tiger
#

Save your bot file in a folder and then open that folder

sacred sand
#

bot file?

scarlet tiger
#

the .py file bruh

sacred sand
#

done

#

like this?

scarlet tiger
#

Now let me see your terminal

sacred sand
#

in vsc?

scarlet tiger
#

Ye

sacred sand
scarlet tiger
#

Ok now run python your_file.py

sacred sand
#

how is invalid syntax

scarlet tiger
#

You need to put your token lol

sacred sand
#

i did

scarlet tiger
#

Let me see the rest of the code

sacred sand
#

i fixed it

#

it says this now tho

scarlet tiger
#

You need to enable privileged intents from the Discord developer portal

sacred sand
#

i looked around for that but i couldn't find it

scarlet tiger
#

!message-content-intent

unkempt canyonBOT
#
Discord Message Content Intent

The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."

The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.

Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:

intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents

bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor

For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.

sacred sand
#

i have to put that code in?

scarlet tiger
scarlet tiger
sacred sand
scarlet tiger
minor geyser
sacred sand
#

ty

scarlet tiger
minor geyser
fast osprey
#

Why not just instruct your bot through discord?

#

You have basically a better terminal already

minor geyser
#

but I think the problem is that I have the input inside the on_ready function

fast osprey
#

Yeah but...you could just do it from discord

#

or is this meant to do one thing and then exit? You don't need a connected bot

hushed meadow
#

Hey

#

I need help with my python code

#

An error occurred: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields: Must be 25 or fewer in length.

#
@bot.command()
@commands.cooldown(1, 300, commands.BucketType.user)  # 300 seconds = 5 minutes
async def viewteams(ctx):
    managers = load_managers()

    if not managers:
        await ctx.send(f"No manager information found. | {ctx.author.mention}")
        return

    embed = discord.Embed(title="Team Information", color=discord.Color.blue())

    for manager_id, team_name in managers.items():
        manager = ctx.guild.get_member(int(manager_id))
        if manager:
            team_role = discord.utils.get(ctx.guild.roles, name=team_name)
            if team_role:
                team_members = len(team_role.members) - 1  # Excluding the manager from the count
                embed.add_field(name=f"Team: {team_name}", value=f"Manager: {manager.mention}\nTeam Members: {team_members}", inline=False)
            else:
                embed.add_field(name=f"Team: {team_name}", value=f"Manager: {manager.mention}\nTeam Members: 0", inline=False)
        else:
            embed.add_field(name=f"Team: {team_name}", value=f"Manager ID: {manager_id}\nTeam Members: 0", inline=False)

    message = await ctx.send(embed=embed)

    # Message timer
    for i in range(30, 0, -1):
        embed.set_footer(text=f"Embed deleting in {i}")
        await message.edit(embed=embed)
        await asyncio.sleep(1)

    await message.delete()```
fast osprey
#

You're sending more than 25 fields in an embed

stark ingot
#

dont cross post, I already answered in your thread

slate swan
#

how does the bot create its own invite if its not even in that server its in and supposed to use my own invite?

stark ingot
#

Please rephrase your question.
You want to know why it says to get a new invite from the "nss portal bot" when the bot is not in the server?

stark ingot
#

I think that is just how discord works. It really means nothing for bots as "asking for a new invite" from a bot is not relevent.

torn orchid
#

Help pls!
Error said that textchannel doesn't have attribute send

fast osprey
#

You're calling send on something that's None

minor geyser
#

basically i was writing it to be able to grab info on a guild or user but was thinking about expanding into some more stuff so i wanted to not have to change the code later which is why im doing it this way now

jaunty cape
fast osprey
#

What are you calling .send on, and why might that be None?

mint elm
#

any idea why this isnt pinging the role correctly?

#

i was told an extra ampersand but even without it it fails

stark ingot
#

You cannot ping roles/people in embeds. You have to put it in the message content

mint elm
#

nvm turns out i was using the wrong role id ☠️

young dagger
stark ingot
#

And the & at the end breaks it

mint elm
mint elm
stark ingot
#

I think it will still display the ping it just will not actually ping anyone

mint elm
#

yea thats even better

#

ty friends

#

actually one more question, this is sending as LITERALLY ## TOP 5 KAISERS instead of

#

TOP 5 KAISERS

#

am i doing something wrong?

patent hull
#

field names don't support header markdown

stark ingot
#

I think bold works, you will have to try it and see

mint elm
patent hull
#

embed description works

#

idk if field values do tho

#

youll have to try

jaunty cape
stark ingot
#

I thought you could make them more bold ¯_(ツ)_/¯

jagged crown
#

@bot.command()
async def delpassword(ctx):
if ctx.author.id in passwords:
del password[ctx.author.id]
passwords()
await ctx.sent(f'Password is now removed')

#

What's my fault here?

scarlet tiger
jagged crown
#

My bud tried it

#

Still doesn't work

jaunty cape
#

and apparently the list password doesn't even exist

#

(or whatever the variable password is)

jaunty cape
#

you shouldn't be using a dictionary for that anyways, you're going to lose all that data the moment you restart your bot

jagged crown
jaunty cape
#

first of all does password exist?

#

the traceback says it doesn't

jagged crown
jaunty cape
#

by making password exist

#

duh

jagged crown
jaunty cape
#

no you have to make a variable called "password"

#

because it clearly does not exist within the scope of your function

#

and based on your testing you already attempted to set the password first

jagged crown
jaunty cape
#

also what you gave us is not helpful

#

you don't tell us where "password" is defined and where the function "passwords()" is defined, and we don't know what it does

jagged crown
jaunty cape
#

wtf is that supposed to mean

jagged crown
jaunty cape
#

and how is that related to what i told you

jagged crown
jaunty cape
#

😐

jagged crown
# jaunty cape 😐

I'm just a teen so while im young need to learn about something I want than playing games

jaunty cape
jagged crown
jaunty cape
#

and how is that related to making a discord bot for your bud?

jagged crown
jaunty cape
#

no you're tripping me

jagged crown
#

Nahh I'm serious

jaunty cape
#

you're not giving the necessary information to make your discord bot work

#

i need to know where you defined the "passwords" variable and what the "passwords()" function does

jagged crown
jaunty cape
#

.-.

#

so what exactly were you asking for help with?

jagged crown
#

lol

jaunty cape
#

😐

sacred sand
#

how do i get the bot token from .env?

uneven wadi
sacred sand
uneven wadi
#

See if that module is there

vocal laurel
sacred sand
#

How do i get just the message that was changed

#

I tried to doing before.Message but it resulted in an error

sacred sand
fast osprey
#

If you're putting peoples' message data somewhere they don't have access to, I hope you're observing the privacy protections you've agreed to in the TOS

fast osprey
#

Nothing in your code suggests that will always be the case, and it's pretty clear what this is meant to do

sacred sand
#

🤓

fast osprey
#

And that's the entire purpose of this bot. To sit in a server with only you and copy your messages.

#

That you send in a server with yourself

sacred sand
#

Yeh

#

Its called learning

fast osprey
#

We're not stupid dude

sacred sand
fast osprey
#

You can learn things that don't violate privacy

sacred sand
#

How do you expect me to learn without using the bot 😭

sacred sand
#

Good job!!!

fast osprey
#

It is very clear what the purpose of this bot is

sacred sand
#

Idk why you're being such an ass about it

#

💀

fast osprey
#

There are a million other things you could be learning in this space. You chose this for a specific reason

sacred sand
#

???

#

😭

#

You're weird

fast osprey
#

Unless you're claiming the only possible thing a bot could do would be to copy people's messages in a way that violates the privacy protections they are afforded by law, there are other things you could build to learn and it's odd that you're picking this specifically

sacred sand
#

💀

#

How do you think mod logs work

#

I bet this server is showing deleted/edited messages in a channel we can't see

fast osprey
#

People doing something doesn't mean that thing is ethical or within TOS to do. You pointing at people doesn't change what you've agreed to

sacred sand
#

You have to be a bot

#

There's no way you're real

fast osprey
#

No I'm just someone who cares about user protections and privacy

sacred sand
#

🤓

#

I choose to learn the messages topic in discord.py
SolsticeShard: "OMGG YOU'RE VIOLATING PEOPLES PRIVACY"

fast osprey
#

Not interested in arguing with someone in bad faith. Ultimately this sort of message dumping is against TOS unless you implement privacy protections, which you've made it clear you don't have any interest in doing so. You saying it's only in your server doesn't change that this code is TOS violating as is and you have no interest in fixing that. You could also choose to learn about those protections, but instead you're being condescending and rude

vocal laurel
thin raft
#

@sacred sand if you want to code something that violates the TOS you signed, you should not be asking how to break it inside that same platform

#

If you do it at least search in a different place 🤦‍♂️

sacred sand
#

There's no warning in it at all

#

and if it breaks TOS then all mod bots would have broken TOS

vocal laurel
sacred sand
fast osprey
#

It breaks tos if the protections aren't put in place

sacred sand
#

and its in the resource in the channel description

sacred sand
fast osprey
#

Their message content is their data, which they have rights to

vocal laurel
#

basically to protect their data as said above

fast osprey
#

When you copy that somewhere, without the correct protections you are stripping them of those rights

#

This is spelled out in the TOS which you have agreed to

sacred sand
#

wdym you can't see it, it literally shows edited in small text when someone edits their tex

#

there i edited it

vocal laurel
#

I can't see the message before it was editied

sacred sand
#

so what now?

vocal laurel
sacred sand
#

Okay

#

so report dyno, it displays edited text before and after in mod logs

vocal laurel
#

A normal person wouldn't be able to see the before message, so there shouldn't be a reason to be storing this

sacred sand
#

go sue them

fast osprey
#

Cool, and that's irrelevant

sacred sand
#

???

#

Its the same thing i tried to do so no its relevant

fast osprey
#

Again, other people violating tos is not remotely relevant to this conversation

sacred sand
#

If you can sue Dyno then i'll admit i'm wrong

#

go ahead

primal cliff
#

why would you want to sue dyno

sacred sand
#

because apparently it breaks TOS

fast osprey
#

It doesn't matter what anyone else is doing

primal cliff
#

also does anyone know a free discord bot hosting service

fast osprey
#

You're just deflecting

primal cliff
#

I heard of glitch and github pages

sacred sand
primal cliff
#

do they work

fast osprey
#

There isn't anything reliable for free eternally, no. They have to make money

vocal laurel
fast osprey
#

Costs money to run servers and they aren't going to spend theirs on you, a rando, forever

primal cliff
#

I tried hosting it on my hp pavilion dv2700

fast osprey
#

They either are limited trials or are so bad they frustrate you into paying

#

!hosting

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku 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.

fast osprey
#

It takes 15 seconds to google discord developer tos

#

Specifically section 5

#

To reiterate, using/storing message content isn't inherently against TOS, just if you do not also implement the required privacy protections. Pointing at other services doing this does not change that, and also does not indicate whether or not they have those protections

mint elm
#

I have this snippet here that checks if a user is already in a certain position on a regional lb (example OCE 1) and its supposed to check if the position in the region is already taken, however it completely goes through and writes it into the file despite already being taken. Screenshot 2 shows exactly what its searching for via a print. Screenshot 3 shows the file being read

fast osprey
#

This would be a lot cleaner (and more performant and safe) with a proper db fwiw

thin raft
mint elm
fast osprey
#

And if a bad write happens, you will corrupt and lose all of your data. This isn't about scale, it's about using the correct tool for the job

#

As is, you're looking for substrings which is probably conflicting with other fields

mint elm
fast osprey
#

Id be more worried about the fact that what you have now will randomly crash and lose all of your data shrug

#

But one thing to do is actually print out the things you're comparing in your if statement, it probably isn't behaving like you expect

mint elm
fast osprey
#

That's not the problem here, you're trying to write to a flat file without atomic writes, which a failure causes the entire file to be corrupted

#

It will only become a problem once that happens and you've lost your data and your app crashes

sacred sand
primal cliff
rugged shadow
#

for gateway bots (like discord.py), you have to get a VPS

exotic hazel
rugged shadow
#

for the interaction based bots, you host an HTTP server and Discord sends requests to it

#

which is pretty neat because some services allow you to serve HTTP requests for free

exotic hazel
#

I see, thanks! That's very cool, because I only wanted to use slash commands anyway

rugged shadow
#

but beware because there aren't a lot of libraries that abstract this functionality really well

exotic hazel
#

Hmmm, they seem to be completely separate for hikari (gateway vs REST)
Does this mean that a discord.py bot, even if it only uses interactions, cannot be hosted as an HTTP bot?

fast osprey
stark ingot
#

I see no reason that logging the before and after content of an edited message would be against developer TOS
From my understanding it would not be for the reasons of

  • There is no expectation of privacy on a discord server so a discord message is not private information
  • The bot is not storing the information but rather posting it
  • In the intended use case the data would only be able to be seen by a subset of the group that could see it originally
  • The bot is exempt from personal data deletion regulations due to the posted information being
  • Non-Private
  • Essential for the functionality of the service (IE a mod log)
    The bot would just need to state this is their privacy policy to be extra safe
fast osprey
#

Nothing in the tos mentions an "expectation of privacy". This is an entirely made up distinction

#

The tos state that you must meet requirements for storing any api data you obtain from discord. It does not make an exception if you happen to also use discord as the storage mechanism

stark ingot
#

And storing API data from a message edit event does meet the requirements

fast osprey
#

No it doesn't

stark ingot
#

How would it not?

fast osprey
#

Are users granted the right to be forgotten when you do so?

stark ingot
#

No, but it falls within the exceptions of the "right to be forgotten"

fast osprey
#

It does not

#

Discord itself is beholden to this, hence why they have feature for it

stark ingot
#

The data is being used to perform a task that is being carried out in the public interest
-# GDPR Source
Publicly available information (such as your address, which is often in public real estate/property records)
-# CCPA Source
Discord has to delete it because they have no need for it.
A logging bot does not have to delete it because the data is being used to maintain an "orderly environment" for public interest and deletion of this data would make the "officials" unable to maintain a "orderly environment"

fast osprey
#

GDPR aside, you don't even have to get into legal aspects. Discord has a privacy feature where users ask for their messages to be deleted, and you as a bot owner have agreed to not interfere with discord privacy features

#

Except to the extent you are required to retain API Data under applicable laws or regulations, you will (1) promptly update the API Data upon request from us or the applicable user, and (2) promptly delete the API Data when: (a) retaining it is no longer necessary for your Application’s stated (and approved through App Review, as applicable) functionality that is permitted under the Terms; (b) you stop operating your Application (whether on your own, due to an enforcement action by us, or otherwise); (c) we request you delete it; (d) the applicable user requests you delete it; or (e) required by applicable laws or regulations. You will give users an easily accessible way to ask for their API Data to be modified and deleted. If you have received API Data in error, you will immediately tell us, delete it, and provide proof of deletion upon our request.

These are separate and in addition to local data privacy laws. None of this cares about "expectation of privacy".

stark ingot
#

The application is not retaining the API Data. If someone screenshots messages on discord, discord is not responsible for hunting down this person and making them delete the screenshot when they need to delete data. The data is no longer in the bots control

fast osprey
#

The bot's messages are in the bot's control. You are using discord as a database

#

That does not absolve you of the responsibilities just because of where you choose to store these things

#

Whether you are reposting my messages in telegram or an excel spreadsheet or discord itself, you have a responsibility to delete my api data when I tell you to. Unless you are claiming that it is a third party, in which case there is a whole separate subsection

faint bloom
stark ingot
#

I prefer py-cord over discord.py.
I have not heard much bad about disnake, I just have not used it

#

Personally I would look at the documentation/examples/guides of each and choose based off of that as feature and structure wise they are all quite similar

fast osprey
#

On the second question, discord.py resumed development and is actively being maintained yes

fast musk
lost scarab
timber dragon
#

dpy upward_stonks

scarlet tiger
#

py-cord >>>

merry cliff
#

whatever works well >>>>>>

mint pecan
#

how can i make a command with both keyword args and normal args?

viscid hornet
#

can you elaborate?

mint pecan
viscid hornet
#

but sure hold on

#

!args-kwargs

unkempt canyonBOT
#
The `*args` and `**kwargs` parameters

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases

  • Decorators (see /tag decorators)
  • Inheritance (overriding methods)
  • Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
  • Flexibility (writing functions that behave like dict() or print())

See /tag positional-keyword for information about positional and keyword arguments

mint pecan
#

i mean a command that support bot args and kwargs

viscid hornet
#

so a command with required arguments and default arguments, yes?

mint pecan
#

yes

viscid hornet
mint pecan
#

like i can specify the arg in command

viscid hornet
#

(..., arg1: type1, arg2: type2, arg3: type3 = None)

viscid hornet
mint pecan
#

!ban @someone
!ban user=@someone

viscid hornet
#

show me an example

mint pecan
#

like this

viscid hornet
mint pecan
#

oh

viscid hornet
#

its already part of discord and by making your own, you're reducing the security of such an action from falling into the wrong hands

mint pecan
#

no im just using it as an example

viscid hornet
#

you're reinventing the wheel by making it square

#

not a good idea

viscid hornet
#

it's already been done

merry cliff
fast osprey
#

The concerns aren't something you could solve with a check

  • your audit log becomes shit because it's your bot doing everything, which is just worse than people doing it themselves
  • you won't reasonably be able to recreate 2FA requirements
  • your bot now has to ask for permissions it doesn't actually need to do things people can already do, which just unnecessarily increases risk if your bot is ever compromised for no actual functional gain

On your initial question you could look into making a flag converter, but there's really not a case where you'd want both. If it's ambiguous enough where flags are useful, you don't want people using positionals

mint pecan
vocal laurel
mint pecan
viscid hornet
viscid hornet
#

if you want individual arguments you can fill in separately then just use slash commands

fast osprey
#

Mixing the two will lead to ambiguous behavior. You do not want this

#

Even better, just move to app commands and eliminate the problem entirely

stark ingot
#

^this
it's kinda what they were designed for. Allow you to have more clarity in your arguments with little to no extra typing on the users part

young dagger
#

Is there a more recent basic cog + extension example?

fast osprey
#

There are live examples for each in the docs. They do not need to come together, and it's important to understand why

young dagger
#

If you have any to provide

fast osprey
#

They're in the docs, as I said

#

Very fast google exercise

young dagger
fast osprey
#

What does "full example" mean

young dagger
#

Dude

fast osprey
#

And how is this not "full"

young dagger
#

Did you check the link?

fast osprey
#

I did.

young dagger
#

The docs are not

fast osprey
#

Because they are not going to rewrite a full bot to explain every concept. What is confusing about the example in the cog docs and how you would integrate it?

young dagger
#

Well that's what I'm looking for

fast osprey
#

You are going to struggle learning if you do not challenge yourself to layer concepts on top of each other

#

People do not have the time to rewrite the entire stack to explain incremental concepts every time

young dagger
#

I'm reading the docs too. I just want an example that's it

fast osprey
#

My advice is to read the new concept and challenge yourself to apply it to what you have vs looking and hoping someone has done that for you in every case. Up to you if you wish to take that advice

#

There are not official examples that do this because they expect you to layer those concepts yourself. There may be unofficial examples but these are not quality controlled or kept up to date

mint pecan
#

how can i make help command display the flags inside a flag converter?

young dagger
#

I added:

    @app_commands.command(name="ping")
    async def slash_pingcmd(self, interaction):
        await interaction.response.send_message(interaction.user.mention)```

But it's says "This applications has no commands"

Any idea why?
fast osprey
#

Are you syncing your commands somewhere? Are you sure this is being added to your command tree?

young dagger
fast osprey
#

Ideally you should only sync when you need to, which is not every time you start your bot

young dagger
#
class SorakaBot(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix="!",
            intents=discord.Intents.all()
        )

    async def setup_hook(self):
        await self.load_extension("cogs.commands")

    async def on_ready(self):
        print(f'Version: {discord.__version__}')
        await self.change_presence(activity=discord.Game(name='League of Legends', type=1))
        print(f'Successfully logged in and booted...!')

    async def sync_application_commands(self):
        await self.tree.sync()
        print("Application commands have been synced.")

    @commands.command(name="sync")
    @commands.is_owner()
    async def sync_commands(self, ctx):
        await self.sync_application_commands()
        await ctx.send("Application commands have been synced.")
#

[2024-09-04 18:01:52] [ERROR ] discord.ext.commands.bot: Ignoring exception in command None discord.ext.commands.errors.CommandNotFound: Command "sync_commands" is not found

#

Am I doing something wrong?

sick birch
#

people also make it a hybrid command so you can use the sync command to sync the sync command

fast osprey
#

You really shouldn't be publishing sensitive owner-only operations as app commands in the first place

fast osprey
#

These have to be externally declared

young dagger
#

Why can't I use

    @app_commands.command(name="ping", description=f"Check {self.bot} current latency.")```
#

It tells me Unresolved reference 'self'

fast osprey
#

You can't use variables like that in statically declared decorators

young dagger
#

Do you know the solution?

fast osprey
#

What are you trying to put in that sub string?

young dagger
#

The bot's name

fast osprey
#

Well your code doesn't know what the bot's name is unless a) you tell it or b) you log in and fetch the app info

#

Very simple answer is to just hard code it in a constant

young dagger
scarlet tiger
young dagger
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2\.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
scarlet tiger
scarlet tiger
young dagger
scarlet tiger
mint pecan
#

How can i make help command display flags inside a command with FlagConverter?

misty widget
#

how to use open cv for robotics

slim bloom
#

code:

#
async def setup_locales(self): 
        os.makedirs('src/locales', exist_ok=True) 
        try:
            i18n.load_path.append(os.path.join('src', 'locales'))  
            i18n.set('locale', 'en')
            i18n.set('fallback', 'es')
            i18n.set('enable_memoization', True)
            i18n.set('format', 'json')
            print(i18n.t('greeting'))
            print('Languages have been setup successfully')
        except Exception:
            print('An error occurred while setup the languages:')
            traceback.print_exc()```

error: When I try to do a print like print(i18n. t('greeting')) instead of the translation appearing, "greeting" appears which it shouldn't, how do I fix it?
#

@hushed galleon

severe rampart
#

You set the locale to english did you not?

slim bloom
mint pecan
#
class A(commands.FlagConverter):
    x: str
    b: int


@commands.hybrid_command()
async def test(self, ctx: commands.Context, *, flag: A):

result:

!test

Arguments:
  flag No description given

default help command does not display A's flags
How do i make it show the inside flags?

fast osprey
#

Why not just make this an app command

mild token
#

Is there a way to set icon from a url of drop-down menu

midnight oracle
slate swan
#
    try:
        result = mongomanager.marketplace_posts_collection.insert_one(document)
    except Exception as e:
        print("error 1:", e)

        try:
            new_data = mongomanager.marketplace_posts_collection.find_one({'_id': result.inserted_id})
            print("new data")
            print(new_data)
            print("----")
            print(self, guild_id, author_id, type)
            await prompt_post_editor(self, guild_id, author_id, new_data, type)
            return
        except Exception as e:
            print("Error 2:", e)
#

why on earth does this happen?

mild token
stark ingot
young dagger
#

What is this about?
5:31 ERROR discord.ui.view Ignoring exception in view <View timeout=180.0 children=4> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='2' emoji=None row=None sku_id=None>

young dagger
fast osprey
#

There's not really a point in putting an error handler in a cog if it's a core part of your bot's infrastructure and not something you'd load/unload. And in general there isn't a point in making cogs that only have one thing, you could just add that thing to the bot on its own, that's just overhead at that point

young dagger
fast osprey
#

I mean it depends on what you want

#

Local error handlers are for logic specific to commands when errors happen. A global error handler is for things you want to happen when any command errors

young dagger
fast osprey
#

I said it was bad to put it in a cog

#

Or rather it doesn't make any sense to

young dagger
#

How else can I add a global error handler for my cogs?

fast osprey
#

That's like taking an apple out of the fridge, putting it into a container, then taking it out of the container so you can eat it immediately

#

@bot.error, or implement it in a subclass of Bot

young dagger
fast osprey
#

Wherever you want it. Things don't have to be in cogs to be in different files

young dagger
fast osprey
#

Personally I'd subclass Bot and put all of my central implementations in it shrug . I also think people obsess way too much about what file they put things in

young dagger
#

This way I don't need to duplicate the loads in every cog

fast osprey
#

Huh?

young dagger
#

So now main.py will act as a fallback for unhandled exceptions

#

Which is the subclass Bot

#

Let me know if there is something I missed

fast osprey
#

You should not be changing presence in on_ready, that can actively disconnect you

#

On_ready fires repeatedly and randomly too

young dagger
#

Under setup_hook maybe?

fast osprey
#

You can pass presence data into the bot's constructor

#

You don't have to change it yourself

young dagger
# fast osprey You don't have to change it yourself

Is this fair?

class Bot(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix=["!", ">"],
            intents=discord.Intents.all(),
            case_insensitive=True,
            help_command=None,
            activity=discord.Game(name='League of Legends'),
            status=discord.Status.online
        )
young dagger
fast osprey
#

You can do that if you want, but do you really want a print every time the bot does a routine reconnect?

young dagger
fast osprey
#

You can make a task that does it once when it initially connects if that's what you want, rather than doing something on every reconnect

#

Up to you, it's just logging

young dagger
fast osprey
#

Nah, it's just going to give you noise about something you probably don't care about

young dagger
#

Hmh intreseting

#

When I do !whois 38630748474022293939 way more than 17-18 digits the bot crashes

#
    @commands.command(name="whois", description="Get user information.")
    @commands.guild_only()
    @commands.cooldown(1, 5.0, commands.BucketType.user)
    async def whois(self, ctx, member: discord.Member = None):
#

[2024-09-06 01:53:28] [INFO ] discord.gateway: Shard ID None session has been invalidated. [2024-09-06 01:53:33] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 0d2cc6f4dfafcf67b98ea53f49327447). [INFO] Successfully connected as Developer Bot.

#

Reconnecting and falling back to the error handler

slim bloom
#

@hushed galleon one question

young dagger
#

lol

#

The bot crashes on exact 20 digits

#

Not 21, 22 etc

fast osprey
#

"Crashes"?

young dagger
fast osprey
#

No, what does "crashes" mean

young dagger
#

[2024-09-06 02:27:05] [INFO ] discord.gateway: Shard ID None session has been invalidated.

#

The session is invalidated. The bot reconnects and falls back to the error handler

young dagger
fast osprey
#

🤨

#

That's not even a valid snowflake, and I don't think anything in the library would straight up disconnect you. Probably something in your code

young dagger
young dagger
fast osprey
#

That is not all of your code

#

Must be something in your code, I'm calling the MemberConverter with a 20 digit id and immediately getting the error id expect

young dagger
# fast osprey That is not all of your code

My full code:

import discord
from discord.ext import commands
import datetime

# Set up the bot with a command prefix and all intents enabled
intents = discord.Intents.all()  # Enable all intents

bot = commands.Bot(command_prefix='!', intents=intents)

check_mark_emoji = '![check_mark](https://cdn.discordapp.com/emojis/1185706844665159820.webp?size=128 "check_mark")'
x_emoji = '![X_](https://cdn.discordapp.com/emojis/1185706862201544774.webp?size=128 "X_")'

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')

@bot.command(name='whois', description='Get user information.')
async def whois(ctx, member: discord.Member = None):
    if member is None:
        await ctx.send("NOT OKAY")
        return

    await ctx.send("OKAY")


# Global error handler
async def on_command_error(self, ctx, error):
    if isinstance(error, commands.NoPrivateMessage):
        return
    elif isinstance(error, commands.MissingPermissions):
        return
    elif isinstance(error, commands.CommandNotFound):
        return
    elif isinstance(error, discord.ext.commands.errors.MemberNotFound):
        await ctx.send(f"{x_emoji} I could not find the user `{error.argument}`.")
        return
    elif isinstance(error, discord.ext.commands.errors.UserNotFound):
        await ctx.send(f"{x_emoji} I could not find the user `{error.argument}`.")
        return
    elif isinstance(error, commands.CommandOnCooldown):
        # Create an embed message
        embed = discord.Embed(title="",
                                description=f"{x_emoji} This command is on cooldown. "
                                            f"Try again in {round(error.retry_after)} seconds.",
                                timestamp=datetime.datetime.now(), color=discord.Color.red())
        await ctx.send(embed=embed)
        return
    else:
        await ctx.send(f"{x_emoji} An error occurred while processing the command.")
        raise error

bot.run('TOKEN_HERE')
fast osprey
#

What are you doing while handling the error?

#

And if you remove this error handler?

young dagger
#

discord.gateway: Shard ID None session has been invalidated. discord.gateway: Shard ID None has connected to Gateway (Session ID: f2d07faabe7c3ee9e5df6d8b57d9b131). discord.ext.commands.bot: Ignoring exception in command whois raise MemberNotFound(argument) discord.ext.commands.errors.MemberNotFound: Member "38630748474022298722" not found. Logged in as Developer Bot (1064279645215793173)

fast osprey
#

And that's the entirety of your code?

young dagger
#

Yes. I created it especially for this example

fast osprey
#

and where are you hosting this? Fetching a user doesn't invalidate your session, you got something fucked in your environment

young dagger
#

PyCharm -> New project

fast osprey
young dagger
sturdy egret
#

Can someone help me with discord embeds and sending images from a file path. Ive got it to send like before the embed gets sent but i cant get it inside of it

unique lichen
#

Is it possible to run a discord bot using eval function?

mint pecan
#

but theyre not showing in help prompt

fast osprey
#

If your goal is to let a user provide multiple optional arguments and to make that easy, app commands are the right tool

unique lichen
fast osprey
#

Why? What is your goal?

midnight oracle
#

Beside the danger of this command, you'll have to adjust your code a little, but yeah. It is possible.

unique lichen
fast osprey
#

Why would that need to be an eval? You could just write the code

golden portal
#

that's usually the issue

#

you didnt even show any code

unique lichen
fast osprey
#

Just...put the code in that program...?

#

Like what is the actual flow here in concrete terms, what are these programs doing

young dagger
dire timber
#

I have a quick question.

How do I make all elements of a view disappear after a timeout if there's no interaction? What I mean by this is, what object do I refer to in order to edit the message without requiring a message/interaction?

Example is

  async def on_timeout(self) -> None:
        for button in self.children:
            self.remove_item(button)
        # or
        self.clear_items()
        
        #The below function call will not work as there won't be an interaction (no button press or similar interaction)
        #await interaction.response.edit_message(view=self)
#

Problem solved now

#

👍