#discord-bots

1 messages · Page 394 of 1

wanton current
#

because .from_dict() is a classmethod, the part before it (title="", description="") doesn't do anything, and you're left with an empty embed

open cobalt
#

and then you pass it into this method and it creates an embed with the given informations

smoky sinew
#

Do not use from_dict

open cobalt
#

yeah I know what this method does, embed has also to_dict method

smoky sinew
timber dragon
#

I think you want to use str.join here for the description

data = {
    "Foo"    : "Bar",
    "Foot"   : "Ball",
    "HOTEL"  : "TRIVAGO"
}
friendly_dict = "\n".join(
    f"{key} -> {value}"
    for key, value in data.items()
)
print(friendly_dict)
# Foo -> Bar
# Foot -> Ball
# HOTEL -> TRIVAGO
# ^ one print

nonfriendly_dict = " AAA ".join(key+value for key, value in data.items())
print(nonfriendly_dict)
# FooBar AAA FootBall AAA HOTELTRIVAGO
vernal socket
#

It has been 10 and ahalf years since I seen this two

ionic pilot
#

crazy

timber dragon
#

Hi

thick birch
#

hi

wanton current
timber dragon
vapid parcel
#

How to get object, ID or Mention Attribute for Sub Commands on App Commands?

slate swan
#

When you walk over commands, it can be a group - if it's a group, then it also have a walk commands method or just the commands attribute

spiral crypt
#

Howdy! I have this role menu being added to a server, the emotes are in a different server the bot is in, is there any way for the reactions being added to be those emotes?

#
emoji_dict = {
        'Party': '![Party](https://cdn.discordapp.com/emojis/1303588149607272468.webp?size=128 "Party")',
        'Challenge': '![Challenge](https://cdn.discordapp.com/emojis/1303588004371107942.webp?size=128 "Challenge")',
        'Crafting': '![Crafting](https://cdn.discordapp.com/emojis/1303587880832204842.webp?size=128 "Crafting")',
        'Valdos': '![Valdos](https://cdn.discordapp.com/emojis/1303586402939830324.webp?size=128 "Valdos")',
        'Divine': '![Divine](https://cdn.discordapp.com/emojis/1303587924771602495.webp?size=128 "Divine")'
    }

I have a dictionary of the ids as I read in an earlier post

    for emote, reaction in just_in_case.items():
        try:
            await message.add_reaction(reaction)

And then just basic reaction adding so im not really sure what else can be done

blissful crane
#

bots have a limited version of nitro, it allows them to react to messages with emojis from any server they're in

fast osprey
#
  • reaction based flows are pretty outdated, and you'll get severely rate limited on reacting. Consider ui elements for things you want users to interact with
  • if you just want to allow users to opt into roles, consider the built-in onboarding options (channels & roles menu)
spiral crypt
#

Plus this looks prettier imo if I can get it to work

#

as well as the mods of the server don't really know what they're doing so I dont think theyll be able to set up the onboarding thing- They said they didn't even know how to add emotes

fast osprey
#

I mean it exists and is a standard way for people to ask for roles in any server they go into, and doesn't rely on a bot constantly waiting and processing reactions, but you do you

spiral crypt
#

And how do they later opt out or into other roles?

glad pivot
#

I hope it will be good!!

#

succes

fast osprey
spiral crypt
sick birch
#

you may also be able to force cache the reaction role message by fetching it but i'm not sure how well that would work/if at all

spiral crypt
blissful badge
#

having a weird issue and running into some issues trying to solve it.

moved my bots to a new VM and getting the modules installed but everytime I try to start it i get the error message "module dotenv not found"

i have installed python-dotenv and even rebooted for good measure but it continues to do it.

is python-env not what I need?

merry cliff
blissful badge
merry cliff
#

did you pip install the library the same place you ran the bot?

#

no just the same VM, the same terminal

blissful badge
#

Yes same VM/terminal

merry cliff
#

are you using virtual environments or installing globally

blissful badge
#

installing globally

merry cliff
#

ok can you paste the install and run command as well as the error?

#

it might have a hidden detail

blissful badge
#

Install (in command line): py -m pip install python-env
run (in command line): poetry run python scnewsbot

slate swan
#

im getting a problem here: from discord.ui import Select, View

merry cliff
blissful badge
#

which is weird ftr because audioop isn't anywhere in my code

#

so unsure why its even throwing that error??

#

weird, its letting me start it from vscode, but not from my .bat file which worked before

#

wtf lmao

merry cliff
#

maybe your vscode is running a different version?

mint pecan
#

how can i type annotate channels?

rugged shadow
#

or whatever type of channel

mint pecan
rugged shadow
#

there was an ABC for those i think

mint pecan
#

discord.abc.GuildChannel?

slate swan
#

yeh

#

!d discord.abc.Messageable # there's also that

unkempt canyonBOT
#

class discord.abc.Messageable```
An ABC that details the common operations on a model that can send messages.

The following classes implement this ABC...
mint pecan
#

how can i make my bot send @ everyone without pinging everyone?

slate swan
#

allowed_mentions kwarg

stark ingot
blissful badge
stark ingot
#

Your choice. Are you sure you installed it in the right place? IE in the same venv as your bot

mint pecan
#

What is the best place to sync commands when my bot is a "slash commands only" bot?

fast osprey
#

"Best" is relative. Really it's entirely your preference given only you should be doing it

#

Sync prefix command, command line param, sync reaction listener, whatever you want

slate swan
#

Sync commands when you react to a specific message with a (specific) emoji

fast osprey
#

You can have this trigger off of literally any event you could perform on discord, or something you could send to the process directly

dense falcon
#

How can I reset the cooldown of a command from another task/function, as well as reset it for all users? I have a daily "checkin" system set up that I want to reset at midnight utc for all users

craggy anvil
#

how to disable timeout on buttons

#

to be clickable forever

blissful crane
#

making a button persistent makes it so you can click the button even after the bot restarts

#

however setting timeout=None will make it so the button never times out (if the bot restarts the button won't respond anymore tho)

slate swan
#

what are good hosts for discord bots

#

idm paid ones just nothing stupidly expensive

fast osprey
#

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

slate swan
#

thank you

mint pecan
#

how can i apply a permissions check for all of the commands inside a cog?

spiral crypt
#

I tried fetching the message but i wasnt able to figure it out

#

So the raw reaction worked and just have checks if the message is the expected saved message id

turbid condor
#

If i remember correctly that's how you do it

fast osprey
#

What type of commands?

leaden olive
#

has anything changed in making discord commands, beacuse i somehow get an error saying Unknown integration after using a command

#

last time i started the bot was in february, so i am a bit outdated

scarlet tiger
obsidian pine
#

Can i use other server's emoji in my bot's if bot is not added in it?

fast osprey
#

No

young dagger
topaz lodge
#

I made a discord bot for a server I moderate and I want to make a easy to use panel that I can distribute among the other mods to control the bot have yall got any tips on how I can use the ui to make the bot function

mint pecan
#

how can i add multiple embeds when responding?

slate swan
#

embeds kwarg

mint pecan
slate swan
mint pecan
#

oh yeah i forgot there are two embeds and embed

slate swan
#

You just can't use both, it's either one or the other

mint pecan
slate swan
#

Docs are pretty clear

mint pecan
#

in my ide it says Sequence

slate swan
#

It's a sort of list

timber dragon
#

Sequence means something iterable technically
Like a list or tuple

obsidian forum
#

Hello

open cobalt
obsidian forum
#

Hru

open cobalt
#

how to send embeds with multiple pages? anybody an idea?

open cobalt
obsidian forum
obsidian forum
shy osprey
#

uhh hello i know that this is the wrong channel to ask in but i dont know why "is there a channel to learn how to code python"

shy osprey
obsidian forum
#

I think i can help

#

Heyy

obsidian forum
#

But there's app easycoder

#

U can use it

#

and i can help too

fast osprey
obsidian forum
stark ingot
shrewd apex
# open cobalt how to send embeds with multiple pages? anybody an idea?

https://gist.github.com/InterStella0/454cc51e05e60e63b81ea2e8490ef140 a tutorial for how to do so but its dependent on this external package/extension also by same creator as discord.py https://github.com/Rapptz/discord-ext-menus
the logic behind it is fairly simple you can implement it yourself as well without any external dependencies
if you are looking for a readymade library here is one of them https://github.com/Defxult/reactionmenu

Gist

A walkthrough on action based pagination in discord.py - Pagination_walkthrough.md

GitHub

Contribute to Rapptz/discord-ext-menus development by creating an account on GitHub.

GitHub

A library to create a discord.py 2.0+ paginator (reaction menu/buttons menu). Supports pagination with buttons, reactions, and category selection using selects. - Defxult/reactionmenu

steep estuary
#

I created 2 new discord bots and the problem is that they work fine for some time but then stop working without giving any error help

#

one bot was working fine for 5 days and then stopped working

fast osprey
#

What does "stop working" entail? Do you have any logs? Is the process itself running?

slate swan
#

i cant figure out how to add this image thing in the title of an embed, can anyone help?

#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent\-style chaining.
slate swan
#

Set the icon_url

slate swan
spiral crypt
#

Is there a way in python for bots, to have like a console command be registered, but with it not like having to always wait for input, cuz that would probably cause other issues right?

fast osprey
#

Id recommend you just send messages to the bot. It's like a strictly better console

mint pecan
#

how can i implement a config manager for my bot?

slate swan
#

Have a database and save the configs for the guild ids

mint pecan
fast osprey
#

You should not use flat files to store things that are changing at run time

#

Even then json is a shit config format

mint pecan
stark ingot
#

Your data most likely still has some structure. Even if some of it is custom, you can store it in a JSON Column

fast osprey
#

You can have non relational databases, but there's really no reason to here. You are declaring a relation

#

You have a finite set of settings

mint pecan
fast osprey
#

Not really sure what you're getting at

mint pecan
#

wdym am i wrong?

fast osprey
#

You use a database to record things that change at run time. Period.

#

You may opt for different database engines depending on the nature of your data

mint pecan
stark ingot
#

Only a little bit. The main reason you dont use normal json is because of the fact that it is just a file, reading/writing can be slow and error prone. A database is designed for reading and writing. Also I have ~5 "normal" columns and 1 JSONB column for my semi-custom key value pairs.

fast osprey
#

Having a suboptimal schema is far less of a problem than using flat files

#

You could in theory shove everything into a giant jsonb column. This would be slow and strip you of data integrity and other benefits of relational data, but at least you'd have atomic read/writes

mint pecan
#

oh right so the solution is switch to a database and jsonb columns btw i also want to "automically" create a discord command for each of the config's flag so that i can change it on runtime with less writing is this bad or a good practice? is there a better way?

fast osprey
#

I am personally suggesting you don't just fall back onto jsonb to avoid thinking about your schema. You do you though

mint pecan
open cobalt
#

getting this error while adding a role : nextcord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions What Permission needs the bot? It has admin permisssion (Test Bot)

scarlet tiger
open cobalt
stark ingot
tired pine
#

Quite obvious, it's one of the checkboxes in the dev portal

#

If it has admin that's not gonna happen

#

Unless you've done something wrong

stark ingot
#

Or maybe...
There is a way to get that error when the bot has admin. And the solution was described in the message directly below the question. The check boxes on the dev portal are just the default permissions the bot will have upon invitation, they can be changed and overridden in channels.

ionic cave
#

Chat 😮

#

Soooo good.

open cobalt
slate swan
#

Not the server for that, go to Fiverr or Upwork

lethal hemlock
west escarp
#

This is a server for learning how to do it yourself, not hiring people. We can't and won't put forth the honestly ridiculous amount of effort required to evaluate job postings and follow the applicable laws for doing so

young dagger
#

Any way to improve this?

# Check for Non-English characters
        elif re.search(r'[^a-zA-Z0-9\s]*$', message.content, re.IGNORECASE):
            modlog_message = "Non-English characters"
fast osprey
#

do it in automod? Thonk

wanton current
#

or do you only want actual letters

young dagger
wanton current
#

yeah

young dagger
wanton current
#

Then your regex approach is probably better

young dagger
mint pecan
#

is automically creating commands good?

blissful crane
mint pecan
blissful crane
#

like wym by creating commands automatically

mint pecan
fast osprey
#

Why would you want separate commands instead of just one command with a parameter? That sounds like api sprawl

mint pecan
fast osprey
#

Making the surface area of your api explode to effectively do N versions of the same thing isn't organized

mint pecan
#

yes thats why i wanted to automate it so

fast osprey
#

I'm talking about organization for your end users, not you

#

You should not be expanding the surface area of your application to do the same thing N times with one very minor thing changing

mint pecan
#

well if i shove it all into one command how would i add stuff like description, custom parameters to each of the config flags then?

fast osprey
#

It doesn't have to be one, but you should make a meaningful decision about your api. Not generate it

sacred grotto
#

trying to use forms with discord bots, anybody have experience with it? need a form to popup when a button is clicked that the user can fill out. using nextcord api rn

#

kinda like this

remote hound
#

how i get custom emojis in here?

slate swan
#

!d discord.ui.button

unkempt canyonBOT
#

@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) being pressed.

Note

Buttons with a URL or an SKU cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) manually instead. This is because these buttons cannot have a callback associated with them since Discord does not do any processing with them.
slate swan
#

emoji kwarg

raven swan
#

can someone familiar with nextcord help me?

slate swan
raven swan
#

i tried to add autocompletion to my application command(slash command) but it gives an error

slate swan
raven swan
#

yup

slate swan
#

and where is autocompleter used

raven swan
#

this is what i needed

#

the docs didnt offer this

open cobalt
#

hey guys been experimenting with the discord api, added a kick command to my bot: ```py
def kick_user(self):
if self.events["t"] == "MESSAGE_CREATE":
content = str(self.events["d"]["content"]).split(" ")
if content[0].startswith("!kick"):
if len(content) == 2:
self.discord_api.kick_user(content[1])
else:
print("Command use !kick user_id")

fast osprey
#

There already exists native features to kick people. Having a bot do it only serves to reduce auditability and security

open cobalt
#

"Remove a member from a guild. Requires KICK_MEMBERS permission. Returns a 204 empty response on success"

#

can someone explain how to add an async aspect to it? Which libraries should I use so that the code be more efficient ?

slate swan
open cobalt
slate swan
#

then why ask if you know?

open cobalt
slate swan
#

You're asking how to add async aspect to something and make it more efficient

#

Using the raw api like you do it not efficient at all and should use existing wrappers

#

If you make your own you should have an advanceed knowledge of the language

#

Knowledge that makes you know that async is built-in in python with asyncio

#

So maybe, ask your questions clearly and rethink about randomly insulting

open cobalt
#

First I dont insult you, second I wrote "experimenting" and third, I know async is built in, and last one I dont make any wrappers!

slate swan
#

Then you have the answer your question already, what's the point in asking things you already know

#

can someone explain how to add an async aspect to it?
You apparently know asyncio, so question answered
Which libraries should I use so that the code be more efficient ?
asyncio, you already know

open cobalt
#

I asked the question because I use a primitive websocket library that doesnt have async to it, and I use requests library which also doesnt have async to it.

slate swan
#

No point in a websocket connection async, you only have a single one that runs in background

aiohttp for non blocking http requests and websocket sessions

open cobalt
#

so aiohttp is for http requests and websocket connections?

slate swan
open cobalt
#

ok I am going to read through it

fast osprey
raven swan
#

nextcords docs are ass

mint pecan
slate swan
mint pecan
#

maybe through tree._call?

slate swan
#
  • you register a function to run, your command, with its respective name
  • discord.py is connected to the gateway and receives events
  • once it receives an INTERACTION_CREATE event it will get the commands you've created and run the command based on the name received in the event
#

now how they're internally called, as in what method is called/executed, would need to read the source

mint pecan
open cobalt
#

yes sir we getting there 😜 ```py
def on_member_join(self):
if self.events["t"] == "GUILD_MEMBER_ADD":
user_id = self.events["d"]["user"]["id"]
role_id_member = xxxxxxxxxx
self.discord_api.add_role_user(user_id=user_id, role_id=role_id_member)

#

works too now we can add a welcome message in the welcome chat hihi

slate swan
#

funny how your methods never have the required arguments to actually do what you want to do

open cobalt
#

what yall think of that ? ```py
if self.events["t"] == "GUILD_MEMBER_ADD":
user_id = self.events["d"]["user"]["id"]
role_id_member = xxxxxxx
self.discord_api.add_role_user(user_id=user_id, role_id=role_id_member)
self.discord_api.create_message(channel_id=xxxxxxx, payload={"content":f"Welcome {self.events["d"]["user"]["username"]} to the the server. Have fun and enjoy the trip!"})

slate swan
#

In need of lots of abstraction

#

And checking for if self.events["t"] == "GUILD_MEMBER_ADD": at the beginning of a on_member_join function is kinda weird

#

Should check for the events, parse the data and send that over to the function as argument

open cobalt
#

I have just worked a little bit with the discord api so I am kinda exploring and let me have fun but thanks for your inputs

slate swan
#

Man if you're getting that defensive and pissed when you're the one asking for feedback, just don't ask already

sacred grotto
#

anyone have experience with selfbot development?

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

slate swan
#

Selfbots are against discord tos and will get yourself banned

sacred grotto
#

its completely for a non-malicious purpose

velvet compass
#

Doesn't matter

slate swan
#

Doesn't matter, selfbots are against tos regardless of what you do

open cobalt
#

I am not pissed but you can tell me what you mean by parse data send it as an argument etc with examples not just with theory but ok, so i can implement it

sacred grotto
#

alr thanks ig

open cobalt
sacred grotto
#

this dudes been typing for 5 mins holy hell

open cobalt
#

wow, and so. Teaching needs his time and finding the right words!

slate swan
# open cobalt I am not pissed but you can tell me what you mean by parse data send it as an ar...

Then ask.

Parse data as in you get the data in the d field based on the event, the fields are listed in the docs.

E.g. the guild member add event returns a member object, which will always have the same fields.

So you can parse that JSON data into a custom member class you'll create. Then you can pass that along to your method.

if self.events["t"] == "GUILD_MEMBER_ADD":
    # parse the content of "d"
    member: Member = ...
    # use that parsed data for your method
    self.on_member_join(member)

Then you can use the class directly in your function, e.g.

def on_member_join(member: Member):
  print(f"Member {member.user.username} joined")
open cobalt
#

Thanks Krypton! I will have a look after a break and try to implement it. When I have further questions, I will post them here

slate swan
#

Then not sure how your internals work, but self.discord_api.create_message is maybe the wrong naming, something like self.http.create_message is better

#

And for self.discord_api.add_role_user(user_id=user_id, role_id=role_id_member), adding a role requires the guild id, not sure where you get that one from. Same for self.discord_api.kick_user(content[1])

#

You can't add a role based on its id to a user based on its id, you need the guild id.
You can't kick a user just based on its user id, you need the guild id.

open cobalt
#

the testbot is only for my test server so the guild id is stored no worries

slate swan
#

Endpoints are PUT /guilds/{guild.id}/members/{user.id}/roles/{role.id} and DELETE /guilds/{guild.id}/members/{user.id}

#

Right then it makes sense, just make sure the bot is not in other servers if you don't read the guild id from the events you receive

open cobalt
slate swan
#

Then go for _http

toxic notch
#

Can i ask for codes? the code that im looking for is a way to put the output in a channel like a Bot logs

sacred grotto
#
# Modal form input
class FormModal(nextcord.ui.Modal):
    def __init__(self):
        # Create a text input field for the modal
        super().__init__(title="Purchase Form")
        self.add_item(nextcord.ui.InputText(label="What are you buying?", placeholder="Units, Items, Gems", required=True))

    async def callback(self, interaction: nextcord.Interaction):
        # Capture the user input from the modal
        user_input = self.children[0].value
        await interaction.response.send_message(f"User is buying: {user_input}", ephemeral=True)

tried to make forms like Tickets bot has, completely lost to what im doing as I've never worked for nextcord API before, please help!

#

heres the goal form

slate swan
wheat sable
#

help

vocal snow
toxic notch
civic fractal
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

toxic notch
#

Im having a hard time doing self learning

#

cuz everything on YouTube is for windows or smth like a computer or laptop

civic fractal
#

it is absolutely worth the investment to purchase a computer if you want to learn programming

#

you can probably get one for <$100

toxic notch
#

:(

civic fractal
#

okay then 6,000 of your currency

toxic notch
fast osprey
#

Your first step is going to be stop using YouTube for educational content

toxic notch
#

Like yt is the only place that i can learn

#

rn

fast osprey
#

It's not

toxic notch
#

Where else can I learn python?

fast osprey
feral holly
fast osprey
#

youtube content, especially in this sphere, is produced by people in their basement who want internet points. It is not quality controlled, it is not updated. It's one dude making shit up 99% of the time

feral holly
#

maybe

#

but not all of them

fast osprey
#

And beginners are not going to be able to tell the difference

feral holly
#

yeah man sometimes

open cobalt
#

hey guys, just updating you. I have made a small approach and implemented a user object into my bot, so we can extract the username and id

open cobalt
#

what casn I improve ```py
if events["t"] == "GUILD_MEMBER_ADD":
user_obj = User(events)
self.client.on_user_join(user_obj)

blissful crane
#

the naming. members are members and users are users. Idk what you call users if you're calling members users but it's best to stick to the originally provided name to avoid confusion

open cobalt
blissful crane
#

nice

leaden olive
#

did anything changed with the .url attribute?

fast osprey
#

None has never had a .url

small gale
#

hello! got a question about something, using discord.py, not sure if their was a new update that came through or something because lines 7 and 9 are not working anymore so I was wondering how I can get it fixed

#

line number 9 is where i got the major problem from the looks

timber dragon
#

That's a syntax error

#

You can't leave functions empty like that in python

And what are those imports doing in teardown

small gale
#

and i am not sure how to fix it me and my friend do this together and he is the smarter one and isn't responding to my dm's...

timber dragon
#

You might wanna refresh your python knowledge

#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

small gale
#

yea i am confused tbh

timber dragon
#
# invalid:
def my_func():

# valid:
# Invalid if the above function isn't removed or given content
def my_func():
    ... # placeholder
small gale
#

let me see if i can find the file my friend sent me

open cobalt
#

you define a func in python like that: ```py
def func(param):
..........instructions

def means define

small gale
#

if it doesn't work let me know

open cobalt
#

what means that parrot reaction?!

small gale
#

idk tbh

#

i never put it

timber dragon
#

Repeating what has been said already

open cobalt
#

bruv chill holy

timber dragon
#

I'm chil? Lol

open cobalt
#

when you get so pissed from that then I am sry but I wanted to help

timber dragon
small gale
#

sooo that kinda doesn't help

open cobalt
#

or just connect to the websocket and make http requests

timber dragon
small gale
#

yea i got no idea if he used chatgpt or what, or maybe he used a yt toturial

#

idk tbh

open cobalt
#

chatgpt is not always good. It makes mistakes too like a human does.

small gale
#

yea ima go ask him idk wtf is going on anymore tbh

open cobalt
#

what project are you guys aiming for?

small gale
#

multiple propose bot for fun but i might use it to become a real dev

open cobalt
#

nice

small gale
#

yea i got 2 projects going one that is javascript and the discord.py one

open cobalt
#

yeah sounds cool

small gale
#

doing 2 code langagues is hard but i need to figure out which one i am going to use mainly

open cobalt
#

so you are familiar with javascript?

small gale
#

nope

#

1st time coding tbh, use to use botghost but that got old real fast

open cobalt
#

ok, dont know about that

small gale
#

don't use botghost it is bad

#

like short cuting developing

open cobalt
#

ok googled it, it is a botmaker

small gale
#

yea and they call it "the best" but they got major issues

#

like rn with shards going offline

#

had all my bots go offline like all day because of it

wheat sable
small gale
#

which

#

on 2nd though is harder

wheat sable
small gale
wheat sable
slate swan
small gale
vapid parcel
#

@hushed galleon, I was wondering if I could talk to you in dms? I have something to ask you. But no channel would fit here, its something personal to you.

leaden olive
#

where can i find that part of the error in the code

dense falcon
#

How can I reset the cooldown of a command from another task/function, as well as reset it for all users? I have a daily "checkin" system set up that I want to reset at midnight utc for all users

open cobalt
#

guys, I need some advice. I struggle a lot with the member object and dont know how to start , so far I have this but I dont know if that is kinda messy to do: ```py
class Member:

def __init__(self, event):
    self.member = event["d"]["user"]

@property
def username(self):
    return self.member["username"]

@property
def id(self):
    return self.member["id"]
wanton current
#

are you making your own api wrapper

open cobalt
velvet compass
#

!cban 1114384953329860710 NSFW gif

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @sharp crane permanently.

rotund flame
#

wow.

strange prairie
#

does anyone know how to check if the bot has permissions to timeout a member?

sick birch
#

Hey guys,

How do i install the audioop module?

patent hull
ionic pilot
#

where is discord.py stored and where do i find it in a docker enviroment

wanton current
#

it is stored where all of your other pip packages are stored

ionic pilot
#

yeah i don't really know where that is

wanton current
#

if you're not using a venv, you can check by doing:

import sys
print(sys.path)

and then it's in the site-packages for the python version you're using

ionic pilot
#

yeah i know

#

but there is no site packages

#

there is no python3.13

#

the folders dont exist

slate swan
#

/usr/local/lib/python3.13

#

And 3.13 isn't supported by python api wrappers, just hikari iirc, either way

open cobalt
#

hey krypton

stark ingot
slate swan
#

there has been other issues

open cobalt
#

y'all would approve ? ```py
def on_member_leave(self, member: Member):
self.http.create_message(channel_id=xxxxxx,
payload={
"content": f"User {member.username} has left us. Till next time buddy ):"})

slate swan
#

Looking good, payload could be updated a bit though

Build the payload in the create_message function. Make the rest normal arguments of the function, e.g.

self.http.create_message("Hello world", channel_id=...)
open cobalt
#

mhh ok, yeah, you right, just write a string not a dict, ok gotchu

#
self.http.create_message(xxxx,  f"Member {member.username} has left us. Till next time buddy :(")
#

it works sounds great

slate swan
toxic notch
#

Uhh Theres an error on line 215, but my code only consists of 89 lines

#

Wth

#

!source

unkempt canyonBOT
stark ingot
#

It is probably line 215 in a different file within your discord library. If you post the traceback we can probably help

toxic notch
#

the traceback is long, is that ok?

slate swan
#

Does discord py support user-install?

toxic notch
#

im kinda new and still learning python

#

also whats user-install?

slate swan
#

its a app not a bot

#

User-Install-Application

toxic notch
slate swan
toxic notch
#

or warning them

slate swan
#

No not the bot sending them a message

toxic notch
slate swan
#

never mind bro im going to google

#

yep

toxic notch
#

bruh

slate swan
stark ingot
stark ingot
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

slate swan
stark ingot
#

I dont know discord.py I just know that they support it. You could join there support server and ask or what for someone else.

toxic notch
stark ingot
#

No you paste your code on the website, click save, then copy the link here

stark ingot
#

The error says what is wrong, the Member object has no attribute user
Did you mean their username, their mention, their id?

toxic notch
#

not {member.mention}

stark ingot
#

Yeah, but what is your goal with {member.user}? A member is a user so all the information you need is already in the member object.

toxic notch
stark ingot
#

So it sounds like you probably want to use the mention parameter instead. {member.mention} just use this like you said above

toxic notch
#

oh ok

toxic notch
#

I wasted So much time

#

Thx for the help anyway

mint pecan
#

why is my mention having two @s?

wanton current
#

Because the role is called @ everyone, not just everyone

ionic pilot
toxic notch
#

Who has a link for documentation or crash course for a Discord bot

#

Please i really need it and want it

open cobalt
#

just make http requests

toxic notch
open cobalt
open cobalt
#

it is on the developer portal

toxic notch
#

channel desc?

#

ok

open cobalt
#

or youtube yeah

#

but i dont know abou that

#

you think youtube would help you @toxic notch

toxic notch
#

Theres no helpful info for A discord bot it only shows "How to make a Discord bot without coding" Type of shit

open cobalt
#

You have experience with python?

lofty pecan
#

I need some help with Modal. I can't seem to find examples using cogs, it's always a single file execution and not a cog added to the bot. I want to make form basically, and I found it randomly, if anyone has some ressource to share :)

sweet brook
#

H

#

I'm a python beginner

lofty pecan
toxic notch
#

i admit that im new

lofty pecan
#

You can just download the repo

lofty pecan
toxic notch
#

im on mobile

lofty pecan
#

You don't code on a PC?

toxic notch
#

4GB of Ram

#

32 GB of Memory

#

Mediatek cpu

lofty pecan
#

For python that's enough

#

You're not gonna build 3d engine it's fine

mint pecan
#

how can i make an alt detection for my bot?

tawny junco
#

And I learned Python on my phone

#

Also made a discord bot

dense falcon
#

how can I reset the cooldown of a command for all users?

timber dragon
#

Reload the cog/bot

dense falcon
#

is there a more "efficient" way? not complaining about the answer, thanks for it, but i want to know if there's a better way that doesnt involve restarting an entire section of the bot

open cobalt
#

hey yall

#

what is that for a reaction?

#

he gave you a link to the docs

#

why question mark?

#

@dense falcon

dense falcon
#

linking the docs without saying a thing isnt exactly helping (especially when ive already read them over like 10 times 😭)

wanton current
#
cmd = bot.get_command("cmd")
cmd.cooldown.reset_cooldown()
dense falcon
#

wait does running it without context reset for everyone?

open cobalt
#

willi is prodigy in python and discord.py so he is right

dense falcon
#

hollup just a moment

wanton current
#

yeah you may need a context

dense falcon
#

😭 ill just reset the cog

#

thanks anyway

wanton current
#

the other one was linked to a specific command, not the cooldown itself

mint pecan
#

how can i check if a interaction response is already deferred?

shrewd apex
unkempt canyonBOT
#

exception discord.InteractionResponded(interaction)```
Exception that’s raised when sending another interaction response using [`InteractionResponse`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse) when one has already been done before.

An interaction can only respond once.

New in version 2\.0\.
fervent harness
#

So I am making a battle bot that has an inventory system linked to google sheets. However when I run the battle command, it raises an "'int' object is not callable error." I don't know what that means. Here is the code.

# player1 has heavier attack
if player1.attack == 'Melee' and player2.attack == 'Magic':
  player1.inv[0].damage(player2)
  await ctx.send(f'{player1.id}\'s {player1.inv[0].name} overruled {player2.id}\'s {player2.inv[2].name}. {player2.id}\'s health: {player2.hp}')
elif player1.attack == 'Ranged' and player2.attack == 'Melee': 
   player1.inv[1].damage(player2)
   await ctx.send(f'{player1.id}\'s {player1.inv[1].name} overruled {player2.id}\'s {player2.inv[0].name}. {player2.id}\'s health: {player2.hp}')
elif player1.attack == 'Magic' and player2.attack == 'Ranged':
  player1.inv[2].damage(player2)
  await ctx.send(f'{player1.id}\'s {player1.inv[2].name} overruled {player2.id}\'s {player2.inv[1].name}. {player2.id}\'s health: {player2.hp}')
        
# player2 has heavier attack
elif player1.attack == 'Magic' and player2.attack == 'Melee':
  player2.inv[0].damage(player1)
  await ctx.send(f'{player2.id}\'s {player2.inv[0].name} overruled {player1.id}\'s {player1.inv[2].name}. {player1.id}\'s health: {player1.hp}')
elif player1.attack == 'Melee' and player2.attack == 'Ranged':
  player2.inv[1].damage(player1)
  await ctx.send(f'{player2.id}\'s {player2.inv[1].name} overruled {player1.id}\'s {player1.inv[0].name}. {player1.id}\'s health: {player1.hp}')
elif player1.attack == 'Ranged' and player2.attack == 'Magic':
  player2.inv[2].damage(player1)
await ctx.send(f'{player2.id}\'s {player2.inv[2].name} overruled {player1.id}\'s {player1.inv[1].name}. {player1.id}\'s health: {player1.hp}')
#

Ik spaghetti code

#

I am a bit of a noob

blissful crane
#

you really need to be careful, this looks like it'll get out of hand really quickly and will be daunting to edit in the future

#

either way, please send the traceback

fervent harness
blissful crane
#

the error is probably because player.inv[...].damage is the name of a variable, make sure your variables and methods don't share the same name

#

(without a traceback I can't be sure)

fervent harness
fervent harness
#

I'll be more careful next time

blissful crane
#

gl on your bot

toxic notch
hot holly
#

Getting a KeyError: 0 when trying to get the support server invite. The YML file is to store all the configuration data needed.

blissful crane
#

print important_data, it's a dict not a list

sleek meteor
#

Is there a variable for a users custom status value? Im trying to make my bot send a message in a channel when a user puts a certain phrase in their custom status, it sends the message, but it also resends it when the user goes online an offline

Custom status:

hot holly
blissful crane
hot holly
#

ah kk

viscid sage
#

This is my firt real attempt at making a discord bot and im so happy with the results i just have to share it
what this custom roster does is, it tracks the roles in the server and updates the roster when someone new is added to a role
it also allows you to click on the name of a user in the list and it will redirect you to their user profile
i blocked out any association to the server its from just so that im not promoting it

stark ingot
viscid sage
stark ingot
#

Oh yeah. Dont mean to burst your bubble but that may not show how you want it on smaller screens like on a phone

viscid sage
stark ingot
#

Smart, that is a cool idea/workaround. Keep up the good work!

viscid sage
#

thank you very much

mint pecan
#

how do i make my bot set a permission to this middle slash

blissful crane
#

when editing the overwrite, instead of True/False make it None

mint pecan
#

oh thanks

slate swan
#

Hello everyone I wanna know if it’s possible to create a bot that auto exchange money, like from PayPal to crypto (ltc/btc…) ty for ur answers, the exchange will also take fees while going the transactions like the person send 10€ PayPal and want ltc , she will receive 10€ -6% fees

sand imp
dense falcon
#

i have a task loop set up to restart the cog daily, however it seems to miss the timing it needs. It should be executing at 6am UTC. here's the relevant code - I know the function works since I've ran it from a command.

from datetime import datetime, timezone, time

resettime = time(hour=6, minute=0, second=0)

@tasks.loop(time=resettime)
async def reset_daily(self):
    cog = Profiles(self.bot)
    await self.bot.remove_cog("Profiles")
    await self.bot.add_cog(cog)
    print("Successfully reset Daily Streetpass and Checkin")
sand imp
#

There is no mention of a timezone anywhere so if thats not the case, i would assume it is maybe defaulting to a different timezone?

dense falcon
#

it should be defaulting to utc according to docs, and using time in tasks.loop says it should be executing that time of day

#

i will check again though

sand imp
#

Yeah i just found this example in the docs:

import datetime
from discord.ext import commands, tasks

utc = datetime.timezone.utc

# If no tzinfo is given then UTC is assumed.
time = datetime.time(hour=8, minute=30, tzinfo=utc)

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.my_task.start()

    def cog_unload(self):
        self.my_task.cancel()

    @tasks.loop(time=time)
    async def my_task(self):
        print("My task is running!")```
dense falcon
#

my baaaad i didnt know you had to start a task

#

ive never seen examples in docs tho, where did you find it?

sand imp
#

f i closed it, lemme find it again

dense falcon
#

ahh ty

#

somehow my whole bot refuses to do anything except print to output now so i have some debugging to do before i implement this 😭

slate swan
# sand imp First question you have to ask is, how do i magically convert 1 currency into a ...

Nope I’m not taking about converting a cryptocurrency into a cryptocurrency but a PayPal amount into a crypto currency Wich I will put the stock

For expl :

I have 1500$ in my PayPal account and I will put 1000$ in the Ltc balance of the bot then if someone want to exchange 100$ for expl he send money in the PayPal account and then he paste his ltc addy after that he receive the money in Ltc with fees 6% for expl

tall kettle
#

Any boody here

#

I am new in discord

#

Can any body help me please

slate swan
#

It's hard when you don't ask anything in the first place

tall kettle
#

I want to learn English more

#

How

#

?

slate swan
#

Unrelated to this channel & server

#

Use google or something like that to search for English courses or school

tall kettle
#

What talke this chaneel@krypton.ninja

#

Hello

#

@slate swan

sand imp
#

And not a python discord bot question.

open cobalt
#

Hello Fadi, your on a python discord server. I mean you can learn english by praticing to write here in english and ask your python related questions here. If you want to learn english, you can use software like Babbel or go to an english school in your area.

velvet remnant
#

hi guys i want to make a discord bot for cod 1 servers status

#

but i dont know that much

#

so if someone is really know that much python

#

that he can help mee

#

so plz

#

no one active

#

ahhh

slate swan
sand imp
#

You are essentially operating as an exchange, And exhcnages for one need to be licensed and registered. Secondly they need to adhere to AML and KYC laws...

All depends on your country but i'd be carefull with what you are doing.

Also pay attention to taxes and stuff

rugged shadow
#

this also violates paypal's terms of service

sand imp
rugged shadow
#

😂 lol

sand imp
rugged shadow
#

woah thanks

stark ingot
prisma surge
#

How to setup AutoResponder. Message create

slate swan
#

love ya

slate swan
#

its not youtube😭

prisma surge
#

Discord pybots

fast osprey
#

Will be easier to help if you describe the behavior you want, and also what you've tried and where you're stuck

shell adder
#

im new is this good?

#

and it has a datastore

spiral crypt
shell adder
shell adder
spiral crypt
#

You can keep the decimal if you want, just when you're printing it, i think its math.floor(value)

#

Itll just look nicer

unique lichen
#

how to make a reminder command or a command which pings me daily perodically

edgy grove
#

thats a very vague question

unique lichen
sand imp
hoary maple
#

Hi All, I am working on a project where I have to access servicenow API using the login credentials , extract the data from Api and load to a Postgres DB. Could you please provide me any available references/resources and thoughts for this project. Thank you

stark ingot
#

This is the discord bots channel, you would have better luck asking somewhere more relevant such as making your own help post #❓|how-to-get-help

spiral crypt
#

For a guild role using an id it would be this yeah?

specific_role = discord.utils.get(guild.roles, id=1158834836161691810)
wanton current
#

Yeah, or just guild.get_role(1158834836161691810) if you're going to be using an id anyway.

spiral crypt
#

Okidoki

glass ocean
#

Also round to 2 decimal places only

#

Or round the number to be a whole number

shell adder
glass ocean
#

These are the api’s iib3xu has

#

@zenith cipher

glass ocean
#

It’s unlimited usage and free

dry kelp
#

Quick question
What would be the best way to perform threshold cleanup?
Let's say a user sets a certain amount of actions in a period of 30 seconds (example)
That would mean after 30 seconds i would need to run a task, is there any other way for a better efficiency?
considering tasks can increase memory usage by a lot?

obsidian pine
#

How do i get a category by name?

hasty pike
toxic notch
#

Can i request for an Discord Index like every code for A discord bot? (ex. At bot.command or bot.event)

slate swan
#

We help you with issues with your code

toxic notch
wanton current
#

I believe you're looking for National Geographic

mint pecan
#

How do i cluster my bot?

lofty pecan
#

Error in class won't propagate to command to stop execution

I have a command to send Modals back to back from a single View object:

# Create an instance of the DropdownMenu view for the oc names
                template_selector = MyView(labels=template_names, values=template_names, bot=self.bot)
                await ctx.send(content='**Select the template to use**', view=template_selector)
                await template_selector.wait()  # continues after stop() or timeout```

I use button to confirm entries after the modal is filled to send the next one. But for some reason the code keeps being executed after the `await template_selector.wait()  # continues after stop() or timeout` even if an error is detected in the last modal. 

```python
            try:
                # Create an instance of the DropdownMenu view for the oc names
                template_selector = MyView(labels=template_names, values=template_names, bot=self.bot)
                await ctx.send(content='**Select the template to use**', view=template_selector)
                await template_selector.wait()  # continues after stop() or timeout
                print(template_selector.value)
                # COMMAND STOPS HERE IF THERE WAS AN ERROR IN THE MODAL INPUTS

                # Create instance of the ColorPicker DropdownMenu view
                view = ColorPicker(bot=self.bot)
                await ctx.send(view=view)
                await view.wait()

                colour = view.colour
                await ctx.send(f'You have picked {colour} for your OC!')

                # Prepare the picture to be stored in the database
                oc_picture = await picture.read()

            except Exception as e:
                # Handle any exception, prevent further execution
                await ctx.send(f"Command stopped due to error: {e}")
                return  # Stop further execution if there's an error
#

One of the modal (the last one has the following function):

    async def on_submit(self, interaction: Interaction):
        # Collect and store user input for each field
        for item in self.children:
            self.user_inputs[item.label] = item.value

        # Process the input for Ability Scores and Modifiers
        try:
            ability_scores = self.user_inputs.get("Ability Scores")
            ability_modifiers = self.user_inputs.get("Ability Modifiers")

            scores = list(map(int, ability_scores.split(',')))
            modifiers = list(map(int, ability_modifiers.split(',')))

            # Process the valid data
            ability_data = {
                "strength": scores[0], "dexterity": scores[1], "constitution": scores[2],
                "intelligence": scores[3], "wisdom": scores[4], "charisma": scores[5],
                "str_mod": modifiers[0], "dex_mod": modifiers[1], "con_mod": modifiers[2],
                "int_mod": modifiers[3], "wis_mod": modifiers[4], "cha_mod": modifiers[5],
            }

            await interaction.response.send_message(f'Characters information successfully saved!\n{ability_data}',
                                                    ephemeral=True)
            self.stop()  # Stop the modal to allow the next modal to be sent

            return ability_data

        except ValueError as e:
            await interaction.response.send_message(
                f"Error: `{e}`\n**Please enter exactly 6 values for both scores and modifiers as shown in the placeholder.**",
                ephemeral=True
            )
            raise Exception("Invalid input in ability scores or modifiers.")  # Raise exception to stop command

The exception works just fine, but it doesn't propagate to the command and won't stop it

lofty pecan
#

[ERROR ] discord.ui.modal: Ignoring exception in modal

#

why does it ignote the exception

patent hull
#

To not break your whole bot

obsidian pine
#

How to i get list of users added into channel ovetwrites?

ornate sapphire
#

anyone know how to fix this?

#

@lyric needle

#

sry for ping but taco in rush

fast osprey
#

The error tells you in English where to go and how to fix it

ornate sapphire
#

:l

#

taco got it

#

who knew all that confusing shit its j plain as day fr

tame bay
#

I'm currently working on creating a simple Discord user bot in Python and need some help to get started. This is a new concept for me, and I'm not sure how to approach it. Specifically, I want to know:

  • How to register commands for the bot.
  • What functions are needed to make the bot work.
  • The basic structure or workflow for building the bot.

If someone could share a short example code or point me toward useful resources, it would be a huge help! I've searched through various sites and servers but haven't found anything clear or specific yet.

Thank you in advance for your support! 😊

scarlet tiger
tame bay
ornate sapphire
#

i cant find it anywhere

scarlet tiger
tame bay
scarlet tiger
ornate sapphire
#

i got it tho. I just made it send a another one first

stark ingot
# tame bay i want to make a user bot. i have some idea to make a guild bot with prefix comm...

If you are using py-cord they have a user app example here: https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_users.py
It is pretty barebones, showing only what makes a command a user app instead of a guild app. The other examples on the github repo for app-commands still work the same way so you can reference them as well. The only difference is the contexts and integration_types

smoky sinew
ornate sapphire
rose narwhal
stark ingot
#

The pastebin library had its latest release 8 years ago. So it is probably intended for use with an older version of python. I would look to see if you can find any more up to date libraries to use

#

You may have to create your own api wrapper as it does not look like there are many options. Otherwise you could try to fix the current one

stark ingot
#

I personally use py-cord. I generally do not recommend switching libraries as there is generally little benefit

vocal plover
#

using whatever you're already using is the best thing you can do unless you have a good reason to switch

ornate sapphire
#

trying to make bot reply to a ping of myself

#

I tried this but didnt work

#

anyone know what i gotta put in the parenthesis to make it reply to ping

#

I also tried <@&USERID>

fast osprey
#

Maybe logging that content will help you debug what's happening here

ornate sapphire
#

nothing comes up

stark ingot
#

They mean that for issues like this you can often solve them by printing what you are comparing. For example print the message content so that you can see what you are getting when you ping yourself

coral cradle
#

If your looking for a mention in the message rather than use message.content why dont you look at the message.mentions for your tag ?

coral cradle
#

after that you can do what you like with them

obsidian pine
#

How to make user install commands

scarlet tiger
obsidian pine
# scarlet tiger It's different in every library
import discord, os
from discord.ext import commands
from discord import app_commands

bot = commands.Bot(intents=discord.Intents.all(), command_prefix="!")

@bot.event
async def on_ready():
    await bot.tree.sync()
    print("Bot is ready")
    
@app_commands.command(name="test")
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@app_commands.allowed_installs(guilds=True, users=True)
async def my_command(interaction: discord.Interaction) -> None:
    await interaction.response.send_message('I am installed in users by default!')
#

Why dpy has provided fields then?

scarlet tiger
obsidian pine
scarlet tiger
obsidian pine
scarlet tiger
obsidian pine
#

I only need 2 command in bot i don't have to worry about other library

scarlet tiger
obsidian pine
#

I don't have time for experiments

#

I'm even ready to switch to node if that works

scarlet tiger
obsidian pine
scarlet tiger
#

Are you using a virtual environment?

obsidian pine
scarlet tiger
#

Create another virtual environment and then install there

obsidian pine
#

Install what

scarlet tiger
#

py-cord?

obsidian pine
scarlet tiger
scarlet tiger
obsidian pine
#

I don't care language or library

scarlet tiger
obsidian pine
obsidian pine
scarlet tiger
scarlet tiger
obsidian pine
#

I'm using replit it keeps installing discord py

#

@scarlet tiger you here?

coral cradle
# obsidian pine How to make user install commands

i'm not sure what you mean... like there is cogs with that feature you could load and unload that your @app_commands.allowed_installs(guilds=True, users=True) might represent their use for a standard user, not something i have tried tho, but cogs do.

obsidian pine
#

Slash commands

coral cradle
#

you can send dm's with the bot you can also use commands in the dm wiith the bot but i don't know of any way you can use it like a built-in in any DM. the lines you have as decorators can be set to allow the use of the command in different scopes like a list of guilds or users for example and if you just want it in a dl say false to the guild.

#

in the guild

#

in the DM

obsidian pine
#

Okay worked

#

But is it possible to remove that reply reference thing from user commands and show it as normal message?

slate swan
#

no

stark ingot
#

I thought follow-ups worked on user apps too? Just limited to 5

slate swan
#

you still gotta reply

stark ingot
#

Ah, yeah i forgot that had the little "reply" line above it too

tired garnet
#

Is it possible to

#

send stuff using webhook

#

then get stuff again from that webhook?

#

I hope that possible

#

because i could use discord for accounts then

#

else ill use mysql

fast osprey
#

You should not use discord as a database IMO if that's what you're asking

wise wagon
#

How can I do that on Visual Studio Code when I want to create a command for my bot, it will be in a new file and not everything in one, I know its c something but idk how to use it pls help DM me

fast osprey
#

What library are you using?

ornate sapphire
coral cradle
ornate sapphire
#

Ok ok

ornate sapphire
#

i dont understand what im supposed to fix

slate swan
#

message.mention doesn't exist

ornate sapphire
#

das what he told me to do

slate swan
#

mention.add_reaction neither btw

ornate sapphire
#

hm

#

how do i make it reply when a certain someone is pinged

slate swan
ornate sapphire
#

preferably on mentionc cuz idk commands yet

slate swan
#

!d discord.Message.mentions

ornate sapphire
#

nothing happened when i pinged myself

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

slate swan
#

It returns user objects, not strings

ornate sapphire
#

nothing showed up in console eitha

slate swan
#

Convert that list of user objects to a list of ID

#

There are other methods as well, but probably an easy one to do

ornate sapphire
#

i literally just started and still on youtube videos

#

so idk how to put that into a code

slate swan
#
your_id = 123456789
if your_id in [user.id for user in message.mentions]:
    print("Mentioned")
ornate sapphire
#

W

slate swan
#

Consider learning python before though, discord.py is not really for beginners it's more for advanced people

ornate sapphire
#

so i know basics of python

#

I know the names of everything I just dont know how to put those together to make smth work

slate swan
#

Basics are not enough

ornate sapphire
#

where do i learn

midnight oracle
slate swan
#

Won't work, not how mentions work

ornate sapphire
slate swan
#

Roughly the required knowledge before making a bot

Prerequisites

Some prerequisites for writing a Discord bot in Python.

Required:

  • Primitive data types
  • Operators
  • Control flow
  • Function definitions
  • String formatting
  • Variables, namespace and scope
  • Importing
  • Classes, objects, attributes and methods
  • OOP
  • Data structures
  • Exception handling
  • Console usage, interpreters and environments
  • Decorators

Useful to know:

  • Databases
  • asyncio basics
  • What is "blocking?"
  • Logging
  • Reading documentation properly
coral cradle
#

as said it's an object and you need to "extract" the values you need from it.. i would try a dir on it to find out what it has or read the docs for that item....

ornate sapphire
coral cradle
ornate sapphire
#

:D

midnight oracle
ornate sapphire
#
 channelId=["1126839090587897866", "1126839177976221786", "1126839219738923070", "1117543378872193074", "1117543448698953859", "1117543493724807250", "1117543598494318693", "1120701899939794974", "1120702042801975438", "1124856806976524328", "1123761521512693760", "1123750319508160573", "1123750583183089684", "1125084175163207750", "1125084175163207750", "1125085306215997572", "1125085976386089020", "1125085976386089020", "1124270543437303859", "1117472177298608199", "1129367300609429534"]  
    if str(message.channel.id) in channelId and "@everyone" in message.content:
        channel = client.get_channel(message.channel.id)
        channels = client.get_channel(1126244432719646801)
        embeds=discord.Embed(title="Your message has been deleted", description=f"**Reason:** \n Attempted everyone ping \n \n **Channel:** \n {message.channel.mention} \n \n **Remember to read** [#1117542377880555631](/guild/267624335836053506/channel/1117542377880555631/)", color=discord.Color.purple())
        embed=discord.Embed(title="This action is against server rules", description="Your message has been deleted", color=discord.Color.purple())
        await message.reply(content=f"{message.author.mention}", embed=embed, delete_after=15)
        await message.delete()
        await channels.send(content=f"{message.author.mention}", embed=embeds)```
#

this is the most complex thing ive done

midnight oracle
#

use message instead, and add the reaction to message

slate swan
#

Content is not any better, you're checking for the ID either way. So who cares

midnight oracle
#

Also, to check for a specific user when this one is tagged, you should use ID's

slate swan
ornate sapphire
#

ik but whats the fun in that

ornate sapphire
slate swan
#

Channel IDs are int btw

#

No need to store them as string and then do str(message.channel.id)

#

Just do message.channel.id in channel_ids and store the IDs as normal int

ornate sapphire
#

that woulda been nice to know.... but if it works it works

#

i aint touching shit

slate swan
#

It's just unnecessary convertion

#

You could convert them three times in various other data types and it would still work, it's just pointless and unnecessary

ornate sapphire
#

how long do u think it would take to get the knowledge to make a good bot

#

without u guys help

ornate sapphire
slate swan
#

!e

a = 1
b = 2

print(str(a) == str(b))

Pretty much what you're doing

unkempt canyonBOT
slate swan
slate swan
ornate sapphire
#

hour a day

slate swan
#

Less than a few weeks are more than enough if you put in like 3-5 hours a day

ornate sapphire
#

yesss

pearl bough
#

heyy can we not use that kind of language here please thankss

cold mica
# ornate sapphire tried that

Not sure if you figured it out yet, but pings in messages are formatted like <@USERID>, so pinging you would be @ornate sapphire

#

(And channels are almost the same being <#ChannelID> )

ornate sapphire
ornate sapphire
pearl bough
cold mica
#

this should be:

if '@ornate sapphire' in message.content:
  bla bla bla
ornate sapphire
#

There's a lot of channels... u need to get paid fr

cold mica
ornate sapphire
ornate sapphire
cold mica
#

I mean it's understandable if it's a small server, but idk about big servers

ornate sapphire
#

Yeah small servers are fun to mod

#

Banning people goes hard

pearl bough
cold mica
#

fair

ornate sapphire
#

Ohhhh i djd get a dm

#

It notifies you too?

#

Send me the codes. I need a copy this

#

Fr fr

pearl bough
cold mica
#

idk why im surprised the python discord bot is written in python

#

also, is it on_ready or on_connect that you should avoid using

#

i remember one of them isnt great to use for triggering one time when the bot comes online

#

Anyways, look at my highly over complicated way of reading a token that i made just because i wanted it to be expandable
I made it like a year ago and never got around to making a better solution
(First image is the bot's main.py and the second image is readconfig.py)

fast osprey
#

You shouldn't use any event really for anything you want to happen once

obsidian pine
#

I'm trying to use app command and it works 3/10 times rest of the time it shows this Error

#

@fast osprey

fast osprey
#

happens when you take 3+ seconds to respond

obsidian pine
fast osprey
#

make your code faster shrug

obsidian pine
#

It's just a simple embed command

fast osprey
#

unless it's your network

obsidian pine
#

How can i make it faster

fast osprey
#

anything in your code can slow it down if it's blocking, not just that command

obsidian pine
#

Is there no other solution?

obsidian pine
fast osprey
#

gotta respond within 3 seconds

#

it's either your code or your network

obsidian pine
#

I have it hosted

#

How do i handle this and make it work?

#

@client.tree.command()
async def confirmation(interaction: discord.Interaction, amount: float, user: discord.User) -> None:
    await interaction.response.send_message('I am installed in users by default!', ephemeral=True)

How can this be slow? Rest are only follow ups

#

The issue is definitely network and i cannot fix that on hosting so

fast osprey
#

how have you determined? What's your ping?

obsidian pine
obsidian pine
# fast osprey ^
import discord, os, asyncio 
from discord.ext import commands
from discord import app_commands

class MyClient(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)

    async def setup_hook(self):
        await self.tree.sync()

intents = discord.Intents.default()
client = MyClient(intents=intents)

@client.event
async def on_ready():
    print("Bot is ready")


@client.tree.command()
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@app_commands.allowed_installs(guilds=True, users=True)
async def confirmation(interaction: discord.Interaction, amount: float, user: discord.User) -> None:
    await interaction.response.send_message('I am installed in users by default!', ephemeral=True)
    embed = discord.Embed(title="Transaction Detected", color=0x5865F2)
    embed.add_field(name="Required Confirmations", value="`1`", inline=True)
    embed.add_field(name="Amount Received", value=f"`${amount}`", inline=True)
    await interaction.followup.send(embed=embed)

client.run()
#

That's all

fast osprey
#

can you print/log out client.latency?

obsidian pine
#

Lemme do this

obsidian pine
fast osprey
#

not network then

obsidian pine
#

I don't understand what is wrong emoji_39 emoji_39

fast osprey
#

You could compare the interaction's creation time to the current time before you try to respond

topaz vector
#

What's the best way to reload a bot for all servers (cogs & slash commands & py-cord)

#

as of now i tried await bot.sync_commands() it doesnt work

slate swan
#

I have all 3 downloaded/imported in my code and it says i dont have them? why??

merry cliff
coral cradle
# ornate sapphire Do you have to look at every channel like all the time???

did you sort your problem in the end ? you know if you want to listen with no command for your tag you can just use a listener that will just check every message but it you want it in a command you can do that also, i put above the listener with no command.
Did not notice you wanted a reaction add if it is seen maybe this is more what your after ?

#

You also dont have to explicitly check for the id's either if you dont want that huge list.....

#
 if user.name.lower() == "yak":
     await ctx.message.add_reaction("👻")
slate swan
#

ah

#

Hey guys, is there a public bot on Discord which keeps an eye on Github repositories and posts updates in a server channel when something changes? I been trying to find one but all of the ones I could find are DIY bots. 🫤

slate swan
#

idk if its bot or integration

#

but u can put webhook in github repo

#

that works only if its ur repo or u have admin on one

stark ingot
# topaz vector as of now i tried `await bot.sync_commands()` it doesnt work

This should work, can you try adding the commands you changed to the commands kwarg, if that still does not work set the force kwarg to true with the commands that were changed.
Overall, I generally think the best solution is to just restart your bot and not deal with cog loading and unloading when using slash commands

slate swan
#

You might need to restart the discord client

#

I found that after adding/modifying commands that they wont show until i switch accounts back or restart discord

stark ingot
#

Oh yes, don't know why I did not mention that ^
Try this first
Note that you can use ctrl+r to reload

ornate sapphire
coral cradle
ornate sapphire
#

None

slate swan
coral cradle
ornate sapphire
#

On message

formal basin
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

coral cradle
# ornate sapphire On message
@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    if message.mentions:
        for user in message.mentions:
            await message.channel.send(f"User: {user.name} | ID: {user.id} | Mention: {user.mention} | Name: {user.display_name}")
            if user.name.lower() == "the_tag_here":
                await message.add_reaction('👻')
        await bot.process_commands(message)
harsh orbit
#

can anybody help me with this error

aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]

fluid flame
#

I need help with a discord bot

#

how to fix it

harsh orbit
#

pip install python-settings
I think

timber dragon
#

Most likely just trying to import a local file

sick birch
#

pydantic_settings 👍

fluid flame
slate swan
#

<@&831776746206265384> against discord tos + server rules

dapper token
#

please help me with this problem in my code on_member_remove function is not executing or working.

patent hull
#

explain "not executing or working"

#

does it print the member removed?

fast osprey
#

Also show your intents

dapper token
dapper token
patent hull
#

And in the developer portal?

dapper token
patent hull
#

this is weird then

dapper token
#

this is my code

#

import discord
general = 1304417440587059234
from discord.ext import commands

class Client(discord.Client):
async def on_ready(self):
print("ready")
async def on_message(self,message):
print('recieved msg')
print('recieved message')
if message.content == '!hello':
await message.channel.send('Hi, do you need me? just use !help for commmand help')
async def on_member_join(self,member):
print("Somebody joined")
channel = await client.fetch_channel(channel_id)
await channel.send(f"Hello {member}")
async def on_member_remove(self,member):
print("member removed")
channel = await client.get_channel(channel_id)
await channel.send(f"Unfortunately, {member} has left..., He will be punished for that crime.")

channel_id = 1304417440587059231

intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True
client = Client(command_prefix = '!',intents=intents)

patent hull
#

do you run the client anywhere...?

dapper token
dapper token
#

nvm

#

everything works except

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






#CHANNELS AND THEIR IDS+=======================================
general = 1304417440587059234

class Client(discord.Client):
  

    async def on_ready(self):
        print("ready")
    async def on_message(self,message):
        print('recieved msg')
        print('recieved message')
        if message.content == '!hello':
            await message.channel.send('Hi, do you need me? just use !help for commmand help')
   
        
    async def on_member_join(self,member):
        print('member joined')  
        await member.send('Welcome to DBP!, Enjoy Your Visit. ')
        await client.get_channel(general).send(f"Welcome to DBP {member}!, Enjoy Your visit")
    async def on_member_remove(self,member):
        print('member removed')  
        await client.get_channel(general).send(f"Unfortunately, {member} has left..., He will be punished for that crime.")

intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True
client = Client(command_prefix = '!',intents=intents)

GUILD_ID = 1304417440587059231

@client.tree.command(name='hello',description='Say hello',guild=GUILD_ID)
async def hello(interaction: discord.Interaction):
    await interaction.response.send_message('Hello there!')

client.run('MY KEY
')






#

@client.tree.command(name='hello',description='Say hello',guild=GUILD_ID)
^^^^^^^^^^^
AttributeError: 'Client' object has no attribute 'tree'

#

this aint working

#

and if i change client to bot then the client events wont run

fast osprey
#

Clients don't have a tree

#

You have to make one yourself, or use ext.commands.Bot instead of Client

dapper token
#
import logging
import discord
from discord.ext import commands 
from discord import app_commands

import discord.ext
import discord.ext.commands






#CHANNELS AND THEIR IDS+=======================================
general = 1304417440587059234

class Client(discord.Client):
  

    async def on_ready(self):
        print("ready")
    async def on_message(self,message):
        print('recieved msg')
        print('recieved message')
        if message.content == '!hello':
            await message.channel.send('Hi, do you need me? just use !help for commmand help')
   
        
    async def on_member_join(self,member):
        print('member joined')  
        await member.send('Welcome to DBP!, Enjoy Your Visit. ')
        await client.get_channel(general).send(f"Welcome to DBP {member}!, Enjoy Your visit")
    async def on_member_remove(self,member):
        print('member removed')  
        await client.get_channel(general).send(f"Unfortunately, {member} has left..., He will be punished for that crime.")


class Bot(discord.ext.commands.Bot):

    async def on_message(self, message):
        print('working')

    async def hello(interaction: discord.Interaction):
        await interaction.response.send_message('Hello there!')
    
    async def add_command(self,command):
        return super().add_command(command)
intents = discord.Intents.default()
intents.message_content = True
intents.messages = True
intents.members = True

client = Client(command_prefix = '!',intents=intents)
CommandClass = Bot(command_prefix='!',intents=intents)
GUILD_ID = 1304417440587059231
#

i have no idea where to go from here

fast osprey
#

Yeah you shouldn't be referring to videos at all IMO. It's just randos making stuff up. You should stick to the official docs of the library you're using

dapper token
#

yea videos didnt help at all and i ve read the whole documentation of discord py 10 times atleaxt now but for each event or class there are like 2 lines and no real description or example

#

thats why i am here

fast osprey
dapper token
#

oh thanks

fast osprey
#

Also read the examples in the repo, not just the docs

open cobalt
#

guys, how would you add mongodb to a discord bot. I thought, make a seperate file called database.py and connect to the db and import the file when needed to insert, delete etc. But is that efficient or correct? Pls educate me

fast osprey
#

mongo tends to be a pretty crap db choice anyways, and it's highly unlikely that your data is actually nonrelational

#

what file you put the logic in is pretty much your choice and won't impact things functionally. The logic itself is what matters

open cobalt
#

I use mongodb since it is easy to learn I mean just "dictionaries" so, no database diagramm (hahah) and stuff like that. But you approve my approach for it, I mean It can be also implemented with other databases?

fast osprey
#

You shouldn't angle your design based on what's easiest

#

If your data is relational (it very likely is), you should use a relational database

open cobalt
#

like mysql you mean with the database language sql?

ebon lynx
#

of course, mongo db is No SQL database, so it can be helpful for storing dictionary. but there are some dis-advantages in it. if you can, you can use PostgreSQL database. you can save all type of SQL, NoSQL data in it

open cobalt
fast osprey
ebon lynx
open cobalt
open cobalt
ebon lynx
#

ok

open cobalt
ebon lynx
#

of course, I often used RDBMS recently

#

sql databases have many advantages so it is widely used

#

you want to store chat history in sql db?

open cobalt
#

no, but when I hear relational, than I think of a diagramm where I put every table in a relation. Is it that complicated?

#

@ebon lynx

ebon lynx
#

not at all. it is not so hard work

open cobalt
#

ok, where do you design your relations, word?

#

or any other microsoft product?

sick birch
#

It doesn’t really matter

#

I sometimes prototype in excalidraw

open cobalt
#

sounds great

ebon lynx
#

excalidraw is ok

sick birch
#

Usually you don’t have too many nested relations so you don’t even need something to make diagrams or whatever on

ebon lynx
#

designing diagrams are for full projects in enterprise level

tardy lagoon
#

I forgot to ask this last time, is there any convention or good practice in using one over the other?

fast osprey
#

between what options?

fluid flame
slate swan
#

most likely a file you're trying to import

#

but apparently you don't seem to know that, which makes it probably not your code either lemon_thinking

slate swan
#

Code:

async def roblox(ctx, username):
    await ctx.send(f'Fetching information for {username}...')
    user_info = get_roblox_user_info(username)
    if user_info:
        await ctx.send(f"User ID: {user_info['id']}\nUsername: {user_info['name']}\nDisplay Name: {user_info['displayName']}\nDescription: {user_info['description']}")
    else:
        await ctx.send('User not found.')```

Error:
```line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: tuple indices must be integers or slices, not str```

**Can someone help me**
wanton current
#

user_info is a tuple, but you're trying to index it as if it were a list

#

Can you show the get_roblox_user_info function?

dry kelp
#

Hello! Someone has been telling me that security bot premium, in case of a channel deletion, they would restore ALL messages from that channel, which would mean storing all messages and sending them throught webhook, which technically it's bad practice to do that, since you would overload your database, and would make it a lot slower for indexing, and they responded with "im sure they don't do it that way", Which is impossible to do it in another way, am i right?

Considering you cannot pull off the messages on_channel_delete event once the channel gets deleted, if they said maybe 20-30-50 messages, it would of had been more normal, but all? It's impossible without storing them to a database, right?

Let's also considering the fact that it would require them to store a user object to send the message throught the webhook looking like the user, and also ratelimits for sending messages...

Tell me if im mistaken, thank you.

fast osprey
#

If you're storing users' messages in any fashion, you're subject to the data privacy to sanyways

grand breach
#

if there is anyone who wants to build a discord bot with me and is kinda new to python dm me

whole field
#

PYTHON IS THE BEST

fast osprey
#

What you described is not unique and also very against TOS

whole field
#

i dont do such dumb shit

fast osprey
#

Good joke prettythumbsup

orchid swallow
#

Hello i have created a group command:

    @ecoadmin_group.command(name="removecoin", description="Remove coins from a user's balance.")
    @commands.has_permissions(administrator=True)
    async def removecoin(self, interaction: discord.Interaction, user: discord.User, amount: int):
        if amount <= 0:
            await interaction.response.send_message("You must remove a positive amount of coins.", ephemeral=True)
            return
        self.economy.update_balance(user.id, -amount)
        await interaction.response.send_message(f"Removed **{amount}** coins from {user.mention}'s balance.", ephemeral=True)

Despite of adding '@commands.has_permissions(administrator=True)'
Still the non admin users have access to the restricted commands. Please help 🙂

blissful crane
#

also, you need to put the check on the group parent, not the children

wanton blaze
#

guys i made a bot to remind me when anime epi comes out using web scraping but i wanted to add a funtion to it so that when my leptop or code stops working it should save what anime i asked it to remind and load them up when i run the code again but it doesn't seem to work anybody if has an idea pls help

slate swan
#

!rule 5

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.

slate swan
#

web scraping == against 99.9% of website's tos