#discord-bots

1 messages · Page 397 of 1

runic dawn
#

Oh

rich hedge
#

You wanna build bots for crypto?

runic dawn
#

But if i make a discord bot whit a currency you can buy whit crypto and then you can buy skins whit it BUT you can gamble whit the skins also first your have to change the skins to a another CURRENCY so that it doesnt count

fast osprey
#

That obfuscation doesnt make it not gambling

runic dawn
fast osprey
#

It won't be

runic dawn
fast osprey
#

Sure thing

runic dawn
fast osprey
open cobalt
#

does disocord py store all the guild and its information locally to reuse them ?

uncut bolt
#

I've enabled logging and this is all I get when it reaches line 2
[2024-12-30 20:06:43] [DEBUG ] discord.client: Dispatching event command_error

wanton current
#

yes

fast osprey
uncut bolt
#
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
bot.run('token', log_handler=handler, log_level=logging.DEBUG)```
#

I could've enabled it wrong tbf I've never done it before

fast osprey
#

You can remove all of that and just keep bot.run(token) to get default logging to console

uncut bolt
#

ok

fast osprey
#

You should start seeing way more logs

uncut bolt
#

I'm not seeing any logs with just bot.run(token) though, which is why I added the handler line and stuff

runic dawn
#

Rasberry pi5 or pi4 for bot hosting

uncut bolt
#

I really don't know why my code isn't working since it was working perfectly before now

#

Finally got it to print the traceback and this is what I get:

[2024-12-30 20:31:04] [DEBUG   ] discord.client: Dispatching event command_error
[2024-12-30 20:31:04] [ERROR   ] discord.client: Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/home/user/.local/lib/python3.8/site-packages/discord/client.py", line 449, in _run_event
    await coro(*args, **kwargs)
TypeError: on_command_error() missing 1 required positional argument: 'error'
#

what does this mean?

uncut bolt
#

oh right that's my bad, typo when adding the error handling, the actual error is:

Traceback (most recent call last):
  File "/home/user/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
  File "MAIN.py", line 610, in rules_embed
    await rules.minecraft(ctx)
  File "/home/user/bot/rules.py", line 96, in minecraft
    embedVar = discord.Embed(title="Rules",  type="rich", description="The following rules are subject to change at any time. These rules are not comprehensive and are subject to staff discretion. Failure to comply with staff, disrespectful or not will result in consequences.", color=discord.Color.from_star('0x00ff00'))
AttributeError: 'function' object has no attribute 'Embed'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/user/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1366, in invoke
    await ctx.command.invoke(ctx)
  File "/home/user/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/user/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'Embed'
#

nevermind

#

I'm just an idiot. I named a function "discord" somewhere before this like a muppet so it was calling that instead of the python package

#

Thanks for all your help lol

onyx belfry
#

Hm, i use pycord fr

open cobalt
#

cool, there are many discord api wrappers for python use which you find the best

frank osprey
#

so ah folks.... i need a way to store peoples usernames and a time stamp from when they joined so ...

whats the best way?, context can be given if needed

fast osprey
#

Usernames aren't reliable, people can change them whenever they want

frank osprey
open cobalt
#

maybe id

#

403291785532669954 your user id @frank osprey

frank osprey
#

just for context this is a autokick bot used for a server that want to kick people after say 7 days

nothing bad just automating

frank osprey
#

i know i can use a json file but this is for a server of 500+ people so i though i would be limited

#

also quite new to coding fyi

stark ingot
#

You should probably use the MEMBER_JOIN event. This will give you the member that joined and you can get the time they joined. Otherwise if you are trying to go through existing members you can loop through all the members and there is a joined_at attribute of member objects.

Just a note: Discord has a built in feature called "Prune" that allows you to kick everyone in a discord server if they have not been active in 7 or 30 days.

frank osprey
#

noted thank you

Its for a 18+ id verified server that wants to give a time limit on unverified so when they join they get a limit of say 7 days then they get booted for not verifying

ah ill make it easier cause i cant explain stuff but it goes off a role, user get the unverified role on join and then the bot give a time limit of 7 days and the kicks said user if they still have the role after the 7 days
i can post the code if you want

should have said that at the start sorry

slate swan
#

I have a problem where all my commands are not syncing it's running properly though

#

I checked my code many times too

#

FYI im running it in repliy

#

Replit*

strange belfry
#

Replit?

#

Is that even possible

fast osprey
#

it's possible but not permanently and it's not worth the effort

#

you should switch to an actual host

open cobalt
#

or your own like a raspberry pi 😇

#

I love them

stark ingot
#

I thought I saw somewhere that replit started blocking requests going to discord. I might just be imagining it though

vapid parcel
#

Wondering if there is a on_guild_subscription or one for user too? An event so I can store the info in a backend api instead of using discords db basically.

slate swan
#

though depending what you want to do there are alternative ways of doing it, e.g. message type

vapid parcel
#

ok ty

keen dune
#

happy new years

open cobalt
#

where does discord py or nextcord cache their requests?

#

is it caching? I mean we can get all the guild and users by caching it and not always send requests etc?

unkempt canyonBOT
#

discord/guild.py line 897

return self._members.get(user_id)```
open cobalt
#

ok, but the library does not make any requests, instead looks through a cache/file that stored the guild id with its user etc

slate swan
#

It doesn't make any request for the get_ methods, for the fetch_ it does and also updates cache

#

Cache then gets updated at various moments

#

e.g guilds cache gets populated once when the bot connects to the ws gateway, as they are sent

safe stag
#

how to make premium button

viscid hornet
boreal breach
#

Hey ya’ll I was just curious. I can write python but at the same have also looked into Linux’s commands or more broadly system commands. My point is where should I really get my facts from that is related to commands or intro to Linux/system commands

brittle sage
#

is there any reason why this shouldnt work?

    try:
        url = f"https://pulse.gamercat.website/chat?message={message}&session-id={session_id}"
        response = requests.get(url)
        data = response.json()

        if data.get("success"):
            return {
                "generated_text": data.get("generated_text", "No response text found."),
                "session_id": data.get("session_id", "Unknown"),
                "tokens_used": f"{data.get('prompt_tokens', 0)} prompt + {data.get('completion_tokens', 0)} completion = {data.get('total_tokens', 0)} total",
                "temperature": data.get("temperature", "Unknown"),
                "top_p": data.get("top_p", "Unknown"),
            }
        else:
            return {"error": "API returned a failure response."}
    except Exception as e:
        return {"error": f"Error fetching response: {str(e)}"}


@bot.tree.command(name="ask", description="Send a message and get a response from the bot.")
@app_commands.describe(message="The message to send.")
async def ask(interaction: discord.Interaction, message: str):
    await interaction.response.defer()

    session_id = 'space-hcaz3'

    result = fetch_response(message, session_id)

    if "error" in result:
        await interaction.followup.send(f"❌ Error: {result['error']}", ephemeral=True)
        return

    embed = discord.Embed(title="Response", color=discord.Color.blue())
    embed.add_field(name="Generated Text", value=result["generated_text"], inline=False)
    embed.add_field(name="Session ID", value=result["session_id"], inline=True)
    embed.add_field(name="Tokens Used", value=result["tokens_used"], inline=True)
    embed.add_field(name="Temperature", value=result["temperature"], inline=True)
    embed.add_field(name="Top P", value=result["top_p"], inline=True)

    await interaction.followup.send(embed=embed)```
stark ingot
#

Is it not working?

haughty ore
#

ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'

#

but i got the file named requirements.txt lol

paper fog
#

https://paste.pythondiscord.com/J4QA

Every time I try testing the buttons discord says ineraction failed. I'm fairly new to python and discord bots so I have no idea what's going wrong

fast osprey
#

Are you getting any errors or output?

paper fog
#

no

#

nothing is showing up as an error and the output area is empty (using VS Code)

fast osprey
#

So no logs at all from the library?

paper fog
#

not that im seeing unless im missing it somewhere

#

when i run the script all i get is the notification that the bot connected and how many commands were synced within the terminal

fast osprey
#

Can you show that output please

paper fog
#

this is all I see when I run the script

fast osprey
#

Okay so you are getting logs. Can you check in the developer portal if you've set an interaction endpoint url?

paper fog
#

i have not

fast osprey
#

Odd

#

Can you log in your callback to see if it's getting in there at all?

paper fog
#

how do i do that?

fast osprey
#

Just a print statement at the start of the callback would be good

paper fog
#

doesnt seem like the callback is even working

fast osprey
#

Now that's interesting

paper fog
#

i click the button discord tells me interaction failed then nothing new pops up in the terminal

#

i even tried adding a defer to the callback

fast osprey
#

So one thing is to remove self.view = view; the library automatically attaches the view to a button when the button is registered on that view. Let me look at what might be stopping the callback though

#

So a print on line 70 isn't firing?

paper fog
#

alright well heres how it looks. the idea is to allow users to click the button correaltaed to the role they want to sign up for. the bot then checks to see if their name is on the json file and if not it asks them to type their IGN. the IGN then gets stored in the json so they dont have to type it in everytime and the IGN gets placed under the respective role where the Limits are rn and if the role is full it sends a message back stating the roll is full and doesnt put their name down and/or disables the button altogether

#

yeah nothing is coming back to me when i click any of the buttons

#

i also cant get a command to sync

fast osprey
#

Wait are you calling the command each time?

#

And sending a "fresh" view?

paper fog
#

yes

fast osprey
#

And right after you send it the buttons don't do anything, not even print?

paper fog
#

nope nothing

#

just says interaction failed on discords end

fast osprey
paper fog
#

tell me about it ive been all over google even resorted to using chatgpt for the first time in my life to try and find answers

#

ive tried probably 50 variations over the past 2 days

fast osprey
#

Chatgpt will lie through its teeth lol. This may need a little in depth debugging. The structure here is a little odd

paper fog
#

if youre free for a vc might be easier for me to screen share

#

I am 100% open to completely starting new if i have to

fast osprey
#

Hmmm so all 3 of those messages get sent with a view, and none of them work? One thing to try is making an on_interaction in your bot class with a print in it to see if you're getting the interaction at all

#

At the airport waiting for a flight so my availability is limited 😔

paper fog
#

no worries it is new years

#

yeah so there are 4 embeds that send as different messages 3 embeds have 6 buttons attached to them and 1 has 10 buttons attached

#

so theres 4 of these total

fast osprey
#

Yeah and I'd expect they'd all probably fail in the same way. I'd remove the self.view=view because that might be messing up the internals, then if that doesn't work try logging in on_interaction

paper fog
#

alr i removed the self.view parts lemm test

#

now i get an error

fast osprey
#

Is there any more traceback?

paper fog
#

yeah

fast osprey
#

Now that's a start

#

This error happens if you try to respond to an interaction 3+ seconds after the interaction happened

paper fog
#

ok so how do i fix that

fast osprey
#

Find out what you're doing before that response that could be taking that long, and respond before doing that. Either that or you've got blocking code that's blocking your entire bot

paper fog
stark ingot
#

It is probably your opening of files again

paper fog
#

well here is what its looking like right now

#

like it interacting with the json?

fast osprey
#

The traceback doesnt match the code you just sent

#

Traceback has a response.send_message with view2

#

Whereas it's a followup in the pastebin

paper fog
#

i literally pasted the code after the error so idk

fast osprey
#

Are you sure you're restarting the bot with the updated code and saving?

paper fog
#

yes

#

unless im restarting the bot incorrectly 🥲

fast osprey
#

Unsure

#

But if there's a line of code in the traceback that you don't see on your file, something's off

paper fog
#

the terminal in VS Code locks after i run the bot so i cant type anything so i have to close the terminal then i just run the script again

fast osprey
#

Personally I don't trust vsc and just run it from the command line, couldn't tell you what it's doing

paper fog
#

this is the same script ran in command line

fast osprey
#

That's powershell. From a command line you could run <your python exe> <your file>.py. Or you can try and get vsc working, but if it's running some other code than what you're looking at it'll be hard to debug lol

paper fog
#

ohhh gotcha

#

how do i get to command line then to try it

fast osprey
#

From windows, just start menu -> search cmd

#

You'll need to know where your python installed unless you installed it with the py launcher option

paper fog
#

oh yeah smh im sorry i knew that my brain is just fried from trying to figure this out over the past 2 days

#

idk what happened but i ran the script again and the errors went away

#

still nothing when i test the buttons tho

fast osprey
#

Oh interesting, same code as above?

paper fog
#

yeah

#

i changed nothing just restarted it again

fast osprey
#

Id say remove the view assignment and try logging in on_interaction

paper fog
#

so like view = on_interaction() ?

#

or what do you mean by that

stark ingot
#

*not receive the command interaction that sends the views

fast osprey
#

I don't think they're not getting interactions at all, but rather something is wrong with the button interactions. Might be getting wrong custom ids

#

There's a lot of moving parts here, nothing looks immediately wrong in the code but then again they were running code they didn't think they were earlier so it's unclear what the state is

stark ingot
paper fog
#

gotcha

#

so i should switch this to be on_interaction instead of view? my limited knowledge so far is this is what is creating all the buttons and the view is what lets me link the buttons to the embeds

fast osprey
#

Only reasons why a button interaction wouldn't get dispatched is if the bot restarted, the view timed out, interactions not being received, or the internals being borked somehow

#

The view is the container for all ui components on a message; nothing inherently to do with embeds

paper fog
#

gotcha i just know when sending the message containing the embeds i read to do what i did in the pic to get the buttons attached to the embeds

stark ingot
#

To put it more clearly. You are sending a message that contains an embed and contains a view. The view and embeds are not "attached" They just appear in the discord UI on top of each other

paper fog
#

well yeah thats what i meant by attached sorry bad wording, make them paired up in the message but yeah obviously the buttons arent part of the embed

#

on top of the buttons not working this command isnt even syncing

stark ingot
#

Make sure you reload discord everytime you sync
Ctrl+R I know nothing about discord.py syncing though so cant help you there

paper fog
#

yeah its just the one command cause the other 3 that are syncing had no issue in that regard even without me reloading discord

fast osprey
#

Yeah I think there's an issue with running the code you think you're running

paper fog
#

yeah i might get rid of the buttons and embeds and start them from scratch

#

hmm it seems like there might be something going on between the bots communication with discord

#

cause i just got rid of one of the commands but it's still syncing

fast osprey
#

You aren't running the code you think you are, I'm pretty convinced

paper fog
#

and working even tho i deleted all the code

#

wym by that?

fast osprey
#

You see code A with your eyes, when vsc invokes python it passes code B

#

In this case most likely vsc is confusing you

paper fog
#

gotcha

fast osprey
#

My planes about to take off but I definitely suggest running python manually on command line passing your .py file

paper fog
#

alright ill try that again i couldnt get it to work earlier so ill play around with it some more

fast osprey
#

gl prettythumbsup

wheat summit
#

Quick question, does an on_image function exist? Asking this as I can’t get on my PC right now.

stark ingot
#

I assume you mean an event for when an image is sent in chat?
The answer is no, but you can just use on_message and check for attachments

paper fog
#

@stark ingot i restarted the entire thing cause it was running old code. deleted it, made a new folder, everything and now im running into this

#

looks like a json issue to me

slate fjord
#

bot.command({
name: "generatecode",
code: $setVar[generatedCode;$randomString[10]] // Generate a random unpredictable code $setVar[codes;$getVar[codes],$getVar[generatedCode]] // Add the generated code to the list ✅ Redeem Code Generated: $getVar[generatedCode] $onlyPerms[admin;❌ You need admin permissions to generate codes!]
})

#

Why it was not working

#

My friend made it

#

If you know pls tell

#

@paper fog

#

@fast osprey

sick birch
sick birch
paper fog
fast osprey
#

The formatting matters

#

(Plus json isn't a particularly good config format, and is an awful dynamic data storage format)

paper fog
#

yeah i figured out the issue tho VS Code is running older versions of the code somehow... i deleted all the files and even uninstalled and reinstalled but it keeps happening so I need to figure out how to fix that

fast osprey
#

Big reason why I use vsc as an editor but never run my code from it

teal delta
fast osprey
#

Yup

teal delta
#

I use it for configurations

#

For my projects

#

And you're saying that's bad as well?

wanton current
#

use whatever you want

teal delta
#

Ok

stark ingot
#

It is not terrible for configuration. As long as you are not using it instead of a database. Another option for configuration files is YAML

fast osprey
#

YAML and TOML are a lot more streamlined/readable IMO and give you better typing

sage chasm
sage chasm
bleak schooner
#

I made bot that will do some commands in pydroid 3 and code don't have any errors and said that bot is online as... but didn't recognize commands in server. I gave him all permissions (administrator).

#

Can someone help

sage chasm
#

for the command

fast osprey
#

You should start by never giving your bot admin, that is a massive risk

#

Sharing your code would be a good start, removing any tokens

delicate canopy
#

how do i grab the user nickname? cuz member.name only shows the user name not the nickname

slate swan
#

!d discord.Member.display_name

unkempt canyonBOT
#

property display_name```
Returns the user’s display name.

For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
delicate canopy
#

ty not goint to ask gpt bro said that display_name and name was the same thing

fast osprey
#

Chatgpt thinks that 3 isn't a prime number sometimes. It's stupid as hell, don't ever use it for something you can't independently verify

slate swan
#

GPT thinks that "Strawberry" has 1 r's

open cobalt
#

chat gpt can be useful for quick search or recap, but dont rely on it, since it has mistakes and not a few

umbral flare
#

hey guys, I’m a nooby when it comes to coding a discord bot using Python/vscode and I’m having a issue where in the terminal it’s saying “command not found” even though my code for the said command looks right. I’ve tried ChatGPT and looking online on why this error is occurring. Any support will be appreciated 🙌🏻

stark ingot
#

Can you post the command decorator and function definition

brave mica
#

tryna make a soundcloud bot anyone know a way to get soundcloud auth id

stark ingot
timber dragon
#

Have you read the channel name lol

modern pawn
#

!user

unkempt canyonBOT
#

You are not allowed to use that command here. Please use the #bot-commands channel instead.

old lily
#

who can please help me with making a bot

slate swan
#

This channel is made for that.
If you have any clear questions, just ask and we'll guide you through the solution

old lily
#

im new with python, i dont understand it fully

#

i wanna make a disocrd bot thats why

#

i use python

slate swan
#

Should focus on learning python first

#

Once you've made some toy projects for fun and learned quite some things, e.g. async, classes, etc. etc. then you're good to go with bots

#

Some list of knowledge that is really good to have before making bots

#

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
#

Otherwise you'll have a hard time making bots and it won't be even fun or enjoyable to do

candid briar
#
AttributeError: 'Parameter' object has no attribute 'send'
async def test(ctx, channel: discord.TextChannel | None = commands.CurrentChannel):
    await channel.send()
#

idk what's wrong it should be working as per my knowledge

vocal plover
candid briar
#

how do i differentiate between slash and prefixed command in hybrid command?

wanton current
#

check if ctx.interaction

fast osprey
#

That's usually a sign you don't actually want a hybrid if you're forking logic like that

teal delta
#

😼

#

And it was fun

slate swan
#

ok. never said it's not possible - said you may face different problems and issues.

teal delta
#

Can't deny that

frank osprey
#

chatgpt and a can do attitude with a little bit of swearing.... now thats how its going for me and im learning everyday

slate swan
#

LLMs for discord bots are probably the worst ever

#

Outdated information, bad code and things that shouldn't be done the way it shows or throwing random inexistent things. Just part of how bad LLMs are

viscid hornet
frank osprey
viscid hornet
#

"yeah my car's missing three of its four doors, the engine doesn't work half the time, there's no roof, i lost the keys so i use a screwdriver, the dashboard doesn't exist, and it has two flat tires, but hey - getting a new car is too easy"

frank osprey
open cobalt
#

what is going on here?

viscid hornet
open cobalt
viscid hornet
open cobalt
viscid hornet
open cobalt
#

makes me angry 😠

viscid hornet
frank osprey
#

ah what have i done

open cobalt
viscid hornet
open cobalt
#

this is not to laugh about?!!

open cobalt
viscid hornet
open cobalt
viscid hornet
open cobalt
#

however guys, we need to end this conversation before it is getting out of hand

frank osprey
#

yeah time to go back to helping the peoples code bots

open cobalt
#

you got it!

#

and I use the term robots rather than bots keep that in mind

frank osprey
#

ah fair enough

open cobalt
#

because bot is just a short term of robot

#

robot => bot => automating stuff @frank osprey

frank osprey
#

yeah i got you

open cobalt
#

how nice, do you have a bot online @frank osprey ?

frank osprey
open cobalt
frank osprey
open cobalt
frank osprey
viscid hornet
#

as in one that's played using its API

#

i have one here if you want to test it out

scarlet tiger
frank osprey
#

yeah im not a fan of the d.py slash commands and i dont use the hybrids or prefix commands (no idea why i dont im just a fan of py-cord's slash comands)

scarlet tiger
frank osprey
#

im also trying to figure out how to make one that would do typical conversions like C to f and back cause hell that would be useful

#

tbh i tried a while back and lost the file and i cant remember what i did ...

viscid hornet
scarlet tiger
#

In py-cord it is more direct and the library synchronizes the commands automatically

fast osprey
#

Which is bad

frank osprey
#

well its more so i was first introduced to py-cords slash commands cause there was something with bot.tree.comand not working yet when i started learning how to make bots but after seeing the syntax for d.py it seems you needed to code the command then code the interface then code what it suppose to do

the first thing i learned about py is less code and clean code is better

fast osprey
#

synchronizing is rate limited and an api publish. Doing it automatically is like pushing to git on file save

scarlet tiger
fast osprey
#

It still has a limit, and it's still an api publish. Devs should actually engage and decide when they want to publish

frank osprey
#

didnt i see one of the py-cord devs in here a while back ?

scarlet tiger
frank osprey
#

ohhh fair enough

stark ingot
#

-# oops ping

open cobalt
#

can someone explain what command syncing is? never used this?

frank osprey
#

"Syncing automatically is 100% ok if you make sure you are doing it right"

-# and here's me not really knowing what im doing probably getting rate limited and might get banned from the dev portal

slate swan
#

It's basically registering an application command to Discord

open cobalt
fast osprey
#

this is an incredibly common development pattern

stark ingot
#

Then don't upload the code to your prod bot, or don't restart the prod bot.

#

I feel like you could run into problems if you follow that strategy
Make a command that is not ready
Pivot to another command that you make fully
Sync commands
Now both are available and you might not realize.
And while you could specify the command you want when syncing it is going to be a lot easier to forget to need to do that.

fast osprey
#

Don't know what to tell you that every company I've worked for pushes code to prod that isn't accessible to everyone

#

"only commit stuff that is done" is a pretty ass pattern

stark ingot
#

Why would you ever want unfinished, probably untested, and bug prone code floating around on your main application.

You can't "sync" buttons. If I want to add a new button to one of my views do you suggest I just add the button even if it does not work? Why would you treat commands differently than other forms of interactions. Or for that matter any other code at all.

fast osprey
#

Because you gate it behind code gates. This is literally something that every company does

glad cradle
fast osprey
#

Yes? This is an incredibly common development pattern

#

Or are we ignoring the entire "code gate" thing

glad cradle
#

why would you use that instead of forks or branches

glad cradle
stark ingot
#

I don't think it being a common development pattern makes it a good one though. Lots of people in d.py sync in on ready making it common but still bad practice

glad cradle
#

yeah I agree

fast osprey
#

And every time they do I tell them not to

#

it's not a good idea, just because people abuse dpy doesn't mean its core philosophy is wrong

stark ingot
#

Furthermore, gated code is still finished in some capacity. You would still need to sync commands for anyone to be able to use them in a gated format. You would probably just choose to make it a guild command

fast osprey
#

Yes, in which case you choose when you want it to go live

#

rather than just doing it on startup

fast osprey
stark ingot
#

Or you could just git pull and restart the bot when you want it to go live. This isn't an argument about manually syncing being bad but rather automatically syncing not being automatically bad practice

fast osprey
#

what if anything doesn't work, which is why you test it and then you rely on it

glad cradle
#

yes but you test it before pushing to prod

fast osprey
#

I'm not saying you don't

#

Just that you don't have to publish your api every single time you push

#

Either way you can get to the same end state. I'm just making the point that manually deciding when you want to sync is far less mental burden and less risk for problems than things repeatedly syncing and going live before you're ready for them to be

#

it's literally just typing in one command

stark ingot
#

Then you can do it your way. I have never once not wanted my commands to sync when I update the code. So py-cord, other forks, and their users can do it our way without being told it "is bad", because it is not.

fast osprey
#

And I can disagree with you that it is bad

rustic rose
#

i made myself a auto-leave bot script

stark ingot
fast osprey
#

I was explaining pros and cons, and then you got defensive

#

you are welcome to disagree but saying I'm misinforming without actually proving anything is pretty disingenuous

stark ingot
fast osprey
#

And then I explained why

viral heart
#

I am new here and new to python and coding in general. Could anyone help me with my bot, I don't know if sending the code here is allowed or not but since I don't really know python yet as I am very new and what I have learned I forgot as it was a couple months ago so I used ChatGPT but I can't quite fix everything with it so I do need help. If anyone is willing to help I can send you a DM of the code or send it here if it is allowed.

#

The problem I am having is that I have commands that require user interaction but everytime I do interact with it, it gives me the "This interaction failed" error

fast osprey
#

You can send code here sure, preferably using a paste site

#

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

fast osprey
#

So firstly, libraries like these are highly advanced and rely on a lot of base knowledge. If you're new to python, you're going to struggle without those foundations. You would be well served to do focused projects on individual concepts to build up your skills. ChatGPT and things like it are a crutch, and a poor one at that as they will blatantly lie to you confidently and you do not have the skills to question it yet.

When you say that you're interacting with it and getting that error, what specifically are you doing?

viral heart
#

For the role select I select the role and then it just loads for about 2 seconds and then gives me that error

#

thats the main one I kept trying over and over as the only other interaction one I can't do until i can do that command

fast osprey
#

but running the slash command itself works fine? And you're running that command and immediately choosing an option from the select?

viral heart
#

Yeah

fast osprey
#

So for one, if you want to restrict command usage there's a far better way to do this via the guild settings -> integrations menu. You can prevent people from even seeing/running the command in the first place

viral heart
#

Oh, thats definitly a easier way

fast osprey
#

See if that suits your needs first. The thing to note is that panel can be changed by anyone with admin or manage server, so unclear if that's a requirement or not

#

but it's one fewer thing your bot needs to track and results in a far better ux

viral heart
#

When doing the role override for the command does it make it were that role can't see them?

#

Or do I have to go back into and select the X option

fast osprey
#

You can either opt people in or out. For restricted commands, the easiest thing is to set @everyone to ❌ and whaterver user(s)/role(s) you want to have access to ✅

#

granting overrides denying iirc

viral heart
#

Oh okay, so then my main problem would be fixed by removing the role select command and going about it through the intergrations?

fast osprey
#

That would be my recommendation for easier management and better ux

#

but up to you. If you want to track it in your bot that's fine too then you'll need to do some debugging to see what's going on with the select

viral heart
#

I'll go about it the way you said as it would be easier and also easier for the fact I don't really know how to code yet

fast osprey
#

Did you get this code from someone else?

viral heart
#

No

green jacinth
#

Hey anyone who is familiar with discord.py, whas the newest way to grab message content from a user? I debug and it can detect when a message is sent by a user, but can't grab the content of said message?

viral heart
fast osprey
#

Yeah chatgpt is absolute ass and a lot of this is wrong, like really badly wrong

#

It is trained on old docs and really crappy example code that youtubers shat out

green jacinth
fast osprey
green jacinth
fast osprey
#

you need to request it in code too

#

not just the portal

green jacinth
#

I did on the portal and the code

fast osprey
#

can you show the code?

viral heart
fast osprey
green jacinth
fast osprey
#

and if you didn't make this code yourself you will have no way of knowing what went wrong, let alone being able to fix it

fast osprey
green jacinth
# fast osprey Will need to see more code, preferably the entirety of how you set up the bot an...
def check(m: discord.Message):
            try:
                print(f"Message details -> Author: {m.author}, Channel: {m.channel}, Content: '{m.content}', Bot: {m.author.bot}")
            except Exception as e:
                print(f"Error accessing message details: {e}")
            return (
                m.channel.id == interaction.channel.id
                and m.author.id == interaction.user.id
                and len(m.content.strip()) > 0
            )

        try:
            print("Waiting for message...")
            msg = await interaction.client.wait_for('message', check=check, timeout=60.0)
            print(f"Message received: {msg.content}")
#

The user is prompted to send a number, but it always pullsback as Message details -> Author: shinyqbert, Channel: shinyqbert_t, Content: '', Bot: False

fast osprey
#

I strongly recommend using modals or commands rather than waiting_for a message

#

it's much cleaner code and a simpler ux for the user to know what's expected of them

green jacinth
#

I havent used discord.py for nearly like a year and a half so Im kind of rusty

fast osprey
#

Modals = the pop up windows with input fields asking the user to give you something

green jacinth
#

Ah, okay let me find the document

fast osprey
#

If you want to get this specifically working, will need to see how you're setting up the bot. Preferably just sending all of the code in a pastebin removing any tokens

green jacinth
#

I have a separate file for most things so I can just send over this in a second

#

Just ignore the sqlite section in it

umbral flare
#

New to coding so please explain this in the simplest way possible lol but anyone know why my bot keeps saying command not found?

fast osprey
#

Will need more code

umbral flare
fast osprey
#

Neither, both are ass

green jacinth
umbral flare
green jacinth
#

@fast osprey Also BLESS, i didnt even know about modals, it works like a charm

fast osprey
#

The official python docs/reputable educational outlets for python, the official docs for the library you're using for library specific stuff. Or their support server

fast osprey
umbral flare
# fast osprey Neither, both are ass

Your right, literally just copied a YouTubers code and I’m still have the “command not found” error. I’m been trying to get round this for the past 2 days and having no luck. I give up lmao

fast osprey
#

Youtube is horribly bad, these people just regurgitate code and there's absolutely no accountability mechanism. I'm in a support server and at least half of the errors I get are from people copy-pasting youtube code and having no idea what it's doing or why it doesn't work

viral heart
fast osprey
#

You can't add text boxes directly on a message. What you can do is have a button/select open up a modal which gives a text box

viral heart
#

Do you think you could teach/help me do that?

fast osprey
#

It depends on how much python you understand that you can do on your own without chatgpt. If this is going to be starting python from scratch, afraid I don't have the time

viral heart
#

All I had started to learn which was on my rpi was not related to discord at all and was to just make a pop up that asked a question and you'd type in yes or no and based on the answer it'd give a response

fast osprey
#

The short of it is that you can have a button/select callback respond with interaction.response.send_modal(...), where what you pass in is a Modal subclass. In that subclass you'd declare what text inputs you want with labels/placeholders, and also what to do when the user submits that modal. There's a fairly good example for discord.py here: https://github.com/Rapptz/discord.py/blob/master/examples/modals/basic.py

GitHub

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

viral heart
#
@commands.cooldown(1, 500, commands.BucketType.user)
async def work(interaction: discord.Interaction):
    if payout_settings["min"] == 0 and payout_settings["max"] == 0:
        await interaction.response.send_message("The work command has not been set up yet. Please ask the bot owner to use /set_work_payout.")
        return

    payout = random.randint(payout_settings["min"], payout_settings["max"])
    user_balance = get_balance(interaction.user.id)
    user_balance["cash"] += payout
    await interaction.response.send_message(f"You earned {payout} coins!")

Shouldn't this add a 5min cooldown for when this command can be used for each user

umbral flare
viral heart
#

Same here

fast osprey
#

@commands.x decorators don't work on app/tree commands

umbral flare
fast osprey
#

!d discord.app_commands.checks.cooldown

unkempt canyonBOT
#

@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) and return a value that is used as a key to the internal cooldown mapping.

The `key` function can optionally be a coroutine...
fast osprey
#

You want to use this ^ for cooldowns on app commands

viral heart
#

so @discord.app_commands.checks.cooldown(1, 300,) would give a 5 min cooldown?

fast osprey
#

Yeah it defaults to per user if you don't provide a key parameter

viral heart
#

Okay, I figured that was what the key was for after re-reading a couple times and im assuming it worked for the cooldown as I did the command once and everytime i tried after it said this interaction failed

fast osprey
#

If you're on cooldown, that decorator throws an error so it wouldn't respond to the interaction

viral heart
#

Okay, so it is working then

#

I honeslty have no idea why i made this bot, I already have a bot in my server that does everything it can and more

fair shuttle
#

so my bot send everything in double when i have only 1 instance running any1 have an idea?

fast osprey
#

You're probably calling process_commands when you don't need to

fair shuttle
fast osprey
#

What's your code then?

fair shuttle
#

i can send one of em here

fast osprey
#

Not the command itself

#

It's going to be in a listener or in some way you're setting up your bot

#

The more code you can send the easier this gets

fair shuttle
# fast osprey The more code you can send the easier this gets
from discord.ext import commands
import os
from dotenv import load_dotenv
from discord import Activity, ActivityType, app_commands

load_dotenv()  # If you are using a .env file for your token
TOKEN = os.getenv('DISCORD_TOKEN')

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

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}!")
    activity = Activity(type=ActivityType.playing, name="in devlopement")
    await bot.change_presence(activity=activity)
    await bot.load_extension("cogs.games")
    await bot.load_extension("cogs.trivia")
    await bot.load_extension("cogs.jokes")
    await bot.load_extension("cogs.levels")
    await bot.load_extension("cogs.giveaway")
    await bot.load_extension("cogs.economy")
    await bot.load_extension("cogs.ban")
    await bot.load_extension("cogs.clear")
    await bot.load_extension("cogs.warnclear")
    await bot.load_extension("cogs.kick")
    await bot.load_extension("cogs.warnlist")
    await bot.load_extension("cogs.warn")
    await bot.load_extension("cogs.unban")
    await bot.load_extension("cogs.usersettings")

bot.run(TOKEN)``` this is my main file
fast osprey
#

You shouldn't be doing things in on_ready. It fires repeatedly and randomly

#

And in theory your issue could be in any of those extensions

fair shuttle
#

in one of the extensions

fast osprey
#

Yeah the library already tries to process commands on message

fair shuttle
#

so i have to remove it?

fast osprey
#

If you don't want to process commands yourself again, yes

fair shuttle
#

okay

fair shuttle
fair shuttle
#
    async def on_message(self, message):
        """Handle DMs to the bot."""
        if message.author.bot:
            return

        
        if isinstance(message.channel, discord.DMChannel) and not message.guild:
            guild = self.bot.guilds[0]  
            guild_id = str(guild.id)
            guild_config = self.config.get(guild_id, {})

            if not guild_config:
                print(f"[DEBUG] No guild config found for {guild_id}")
                return

            category_id = guild_config.get("category_id")
            category = discord.utils.get(guild.categories, id=category_id)
            if not category:
                print(f"[DEBUG] Category with ID {category_id} not found")
                return

            print(f"[DEBUG] Category found: {category.name}")

            
            ticket_channel = discord.utils.get(category.channels, name=f"ticket-{message.author.id}")
            if not ticket_channel:
                print(f"[DEBUG] Creating ticket channel for {message.author}")
                ticket_channel = await category.create_text_channel(
                    name=f"ticket-{message.author.id}",
                    topic=f"Modmail ticket for {message.author} ({message.author.id})"
                )

            
            mod_role = guild.get_role(guild_config.get("role_id"))
            if mod_role:
                print(f"[DEBUG] Sending notification to moderators in {ticket_channel.name}")
                await ticket_channel.send(
                    f"{mod_role.mention}, you have a new modmail ticket from {message.author.mention}:\n"
                    f"**Message:** {message.content}\n\n"
                    f"**User Info:**\n"
                    f"ID: {message.author.id}\n"
                    f"Joined: {message.author.joined_at}\n"
                    f"Roles: {', '.join([role.name for role in message.author.roles])}"
                )
            else:
                print("[DEBUG] No mod role found")
                await ticket_channel.send(
                    f"You have a new modmail ticket from {message.author.mention}:\n"
                    f"**Message:** {message.content}\n\n"
                    f"**User Info:**\n"
                    f"ID: {message.author.id}\n"
                    f"Joined: {message.author.joined_at}\n"
                    f"Roles: {', '.join([role.name for role in message.author.roles])}"
                )

            
            await message.author.send("Thank you for reaching out! A moderator will respond as soon as possible.")``` 
this is a part of my code but why when i send the messsage to the bot it doesnt create the channel in the server!
#

and the bot has every permissions tho*

blissful crane
#

you'll have to add some debug prints

fair shuttle
blissful crane
#

so where is it stopping?

fair shuttle
#

and the bot has every perms

fast osprey
#

Your bot should absolutely not have every perm. It doesn't need every perm to do its job guaranteed

#

Starting with a print at the beginning of the listener is a good start to see if the listener is firing at all. If it's not, then you probably have something structurally wrong and we'll probably need the full file

fair shuttle
#

ah i cant send the full file

fair shuttle
fast osprey
#

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

fair shuttle
fast osprey
#

Though it looks like you're just shadowing the on_message method

#

If you define a method with the same name twice, the first one gets overridden

fair shuttle
blissful crane
#

change the method name

fair shuttle
#

ahhhh gotcha

fast osprey
#

You can declare which event you want a listener to listen for in the listener decorator if it doesn't match the method name

#

Or just condense them into one listener, up to you

fair shuttle
#

this is the error

fast osprey
#

Going to need more code and a full traceback, not just the error

#

Also if you're using json files to store data your app generates, that is highly unadvisable. You should use a proper database, json is not a storage format

fair shuttle
fast osprey
#

mysql is a pretty crap db to be honest

#

pretty much any other sql flavor would be better

fair shuttle
fast osprey
#

mysql is not good

#

and the queries will largely be the same for other sql flavors

fair shuttle
#

i heard about mongodb will that be a good one?

fast osprey
#

mongo is worse

fair shuttle
#

lmaoo i need to learn about database

fair shuttle
fast osprey
#

because whatever ticket_data is, it's a string

#

Also I very strongly recommend you don't use channels for "tickets". Channel creation is rate limited and maxed. You'd be far better off making threads in a single static channel, that's what they're designed for

#

They also have vastly simpler permissioning and a much better archival process

fast osprey
#

Yeah it's difficult to trace what's going on here because python is loosely typed. get_or_create_ticket is returning a string, and your comment just says it "gets the ticket" though a ticket isn't a python type

#

Also very helpful to typehint what functions return to make it easier on yourself

fair shuttle
#

ill try that

open cobalt
#

you cant say this is worst this is worse and so on. you need to clarify why for example mongodb is worse than mysql or why is mysql not a good option

hot furnace
#

@slow rampart

slow rampart
#

yup got pinged

fast osprey
#

It takes about 5 minutes of googling either of these db engines to find scores of posts lamenting their shortcomings

#

I can give you the summaries of those but the proof is in the pudding so to speak

open cobalt
#

just not faire makes me angry 😦 😠

fast osprey
young dagger
open cobalt
young dagger
open cobalt
#

wait for @fast osprey response on that

#

I have never used mongodb for discord bot

#

but for a small dating app

#

😎

fast osprey
#

shrug you can get a fork to work for eating soup but doesn't mean it's the best idea

#

At minimum it requires an understanding of what relational data means to make an informed decision

open cobalt
#

...

young dagger
#

My newest addition for my bot is to show mod stats that includes Modmail threads (which are handled by another bot)

open cobalt
#

what are modmails?

#

just mails for the mods? how can I imagine that

young dagger
#

It's a way of contacting staff members

#

Yes

fast osprey
#

Very common use case. User messages bot, bot relays to staff, staff handle, bot replies to user

#

It's a way of abstracting the user from the people/person handling the issue

open cobalt
#

ah ok, so when I want to report someone on the dc the report goes to a staff

fast osprey
#

This server uses one for example

open cobalt
#

and the staff take action on my report

young dagger
#

It's a way of communicating with the staff. Rather than DMing a mod directly, you send a DM to Modmail (the conversation happens between you and the Modmail bot)

#

So that the first available staff member can answer and handle your issue

fast osprey
#

It's a bit more convoluted than the traditional notion of a "ticket" but useful when you want the people handling or taking action to be anonymous and the bot is an intermediate

open cobalt
#

what about a system I thought of, when I type for example !report [user] [reason] the report goes to a report channel with a button attached to clear the report if it is done.

fast osprey
#

That works in that case but doesn't allow for a back-and-forth dialogue if clarification is needed

young dagger
#

It's not ideal if you need to ask them for proof, such as screenshots/recordings or to ask/answer questions

open cobalt
#

yeah true

young dagger
indigo reef
#

hello

#

So im new to python trying to make a basic simple discord bot

#

but im getting errors on very small piece of code can anyone help or tell me whats wrong

frail turtle
#

send

indigo reef
#

k

#

import discord
from discord.ext import commands

client = commands.Bot(command_prefix="!")

@client.event
async def on_ready():
print("The bot is now ready for use!")
print("----------------------------")

@client.command()
async def hello(ctx):
await ctx.send("Hello, I am the Fortnite bot!")

client.run('')

#

heres it i removed the bot token

#

but when i run it this is what happens

#

@frail turtle ?

frail turtle
#

I am trying to figure it out hold up

indigo reef
#

ohk mb

#

for the ping

indigo reef
#

ohk

thorn beacon
#

intents=discord.Intents.all()

#

Add that in your tuple.

golden bane
#

does someone know how to fix this

indigo reef
thorn beacon
indigo reef
#

ok

thorn beacon
#

import discord
from discord.ext import commands

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

@client.event
async def on_ready():
print("The bot is now ready for use!")
print("----------------------------")

@client.command()
async def hello(ctx):
await ctx.send("Hello, I am the Fortnite bot!")

client.run('')

indigo reef
#

thank you

thorn beacon
#

No worries.

indigo reef
#

thanks

#

it finally is online

#

yay

thorn beacon
#

🙂

indigo reef
#

now commands

indigo reef
#

can someone give me like small text on how to make my bot ping the person when he joins and says your the example 3rd member

slate swan
#
  • Listen for member join events
  • Get/fetch the channel you want to send the message in
  • Send the message by using the .mention attribute on the member object
  • Get the length of the members of the .guild attribute of the member object, if you have the members intent you can also use member_count attribute iirc
indigo reef
#

or nah

#

like i have the code im new so i dont know what u just said

open cobalt
#

For example

indigo reef
#

can i show a piece of how the code looks?

open cobalt
#

Yeah why not

indigo reef
#

can i send channel ids here?

#

its not important right?

open cobalt
#

Send the code snippet and people can review

indigo reef
#

heres the code for when it says hello

#

iu want it to mention the user and say ur the ...th or whatever member

stark ingot
indigo reef
#

im trying to make it like this

indigo reef
#

and it displays how many meber he was

open cobalt
young dagger
indigo reef
#

tbh i have no clue on how to do that

open cobalt
#

Just fein it

indigo reef
#

lol

#

im cooked

open cobalt
#

No fein it!

indigo reef
#

bruh help please

young dagger
# young dagger

To mention a member, you would use member.mention and member_count = member.guild.member_count to get the member count, then to print out {member_count}

indigo reef
#

Ohk thanks

#

I don’t know where to place it

#

I’ll just search to find out where to place it

young dagger
#

Put the variable after where you defined the channel and the rest in an f-string

indigo reef
#

K

#

Outside the brackets?

#

Single f string?

young dagger
#

First you need to tell the code that it is an f-string. Do you know how to do that?

indigo reef
#

Like this (f”blah blah”)

young dagger
#

Good

indigo reef
#

Forgot ti close mb

#

Do I make it in different f strings?

young dagger
#

await channel.send(f"Welcome {member.mention}. We've reached {member_count} members!")

indigo reef
#

thanks so much

#

i mightve done something wrong

young dagger
#

It says member_count is not defined

indigo reef
#

can u explain dont give it straight up i need to leanr

#

what variable

young dagger
#

The code doesn't know what you mean by member_count

#

So you have to define it

indigo reef
#

so how do i define it

young dagger
#

member_count = member.guild.member_count

indigo reef
#

k

#

im taking notes

young dagger
#

You could use member.guild.member_count directly but I think this is a good way to learn about variables

indigo reef
#

i do i know where to put it exactly in the line

#

bcz i struggle where to put the code

young dagger
#

If you invited me to your birthday party, would you tell me before or after the party?

indigo reef
#

Before

#

like this?

young dagger
#

So put it before the message, just like the way you defined channel

indigo reef
#

async?

young dagger
#

Show your full code

indigo reef
#

Ok

young dagger
#

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

indigo reef
#

I REMOVED MY TOEKN

young dagger
#

As you always should

#
@client.event
async def on_member_join(member):
    channel = client.get_channel(1324643099187613756)
    member_count = member.guild.member_count
    await channel.send(f"Welcome {member.mention}. We've reached {member_count} members!")
indigo reef
#

im tryna figure out whats going on

#

.

potent fox
indigo reef
#

Ok

potent fox
indigo reef
#

there

open cobalt
#

I see just : channel = client.get_channel(1324643099187613756)

indigo reef
#

wym

open cobalt
#

on the paste

indigo reef
#

i sent the whole code

#

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

open cobalt
#

this link?

indigo reef
#

here

open cobalt
#

mhh

open cobalt
#

it says member_count is not defined

indigo reef
#

and where

open cobalt
#

so you need to define the variable and set the value in it

indigo reef
#

i dunno how to fix thta too

open cobalt
#

please put the whole code in the pastebin you have so far

indigo reef
#

i have

#

done that

open cobalt
#

ok

indigo reef
open cobalt
#

ok, so you get the channel. now you want to send to the channel

indigo reef
#

It sends already I think

#

But I want it to mention the user

#

And say what member he was to join the server

open cobalt
#

wait, I need to look into the docs @indigo reef

#

ok, have it. The on member join event gives you a member object

open cobalt
#

and then you have attributes like guild which gives you the guild object

viral heart
indigo reef
open cobalt
#

and the guild dobject has an attribute member_count

#

so beerhunter is right

indigo reef
#

i dont know what u saying tbh

open cobalt
#

try this code snippet from beerhunter

#

should work

young dagger
indigo reef
#

k

open cobalt
#

otherwise I would say you look into the docs

indigo reef
#

thanks

#

it works

#

thanks @open cobalt and @young dagger

full oar
#

hiya, quick question - is there an api limitation with sending attachment files after updating an embed (unrelated to interaction buttons being used to trigger an edit) ?

#

my bad, should be attachments.

indigo reef
open cobalt
indigo reef
#

Lol

#

I mean like I’m gonna maybe be asking for more help tommorow

indigo reef
#

But I’ll watch some tutorials before I go to bed

#

So I’m not much of a bother

open cobalt
#

a sigma boy is not a bother

indigo reef
#

Gn luicio thanks for the help

open cobalt
#

good night sigma boy

viral heart
#

For my bot, when ppl do commands how do I have it so that only they can see the command they used as to not clutter the channel

fast osprey
#

Which kind of command? Prefix or slash?

viral heart
#

slash

#

I don't like prefix commands so I stick to slash

fast osprey
#

You can pass ephemeral=True into your response

#

makes it only show up for the person who ran the command

viral heart
#
async def info_dayz(interaction: discord.Interaction):
    embed = discord.Embed(
        title="DayZ Server Info",
        description=f"**Server name:** {SERVER_NAME}\n**Server password:** {SERVER_PASSWORD}\n**Server start time:** {SERVER_START_TIME}",
        color=discord.Color.green()
    )
    await interaction.response.send_message(embed=embed)

where would I add the ephemeral=true?

fast osprey
#

interaction.response.send_message(..., ephemeral=True)

viral heart
#

Okay, thanks

viral heart
#

Is there a reason for why when I do / it also shows my other bot that isn't even in the server, I've gone to other servers and it doesn't show in them

#

There's also a bot I've made awhile ago that isn't even active anymore and I've deleted from the developer portal but it also shows

fast osprey
#

probably have a user app command installed

viral heart
#

And do you by chance know how to have a bot connect to nitrado so the bot can get logs from log files

fast osprey
#

I have no idea what nitrado is

#

also try just refreshing your client if you haven't

viral heart
#

I checked both on my pc and phone

viral heart
fast osprey
#

But did you refresh your client on your pc

viral heart
#

Just did and there still showing

fast osprey
viral heart
#

Damn, gotta hope no one else can see them then since for some reason the commands from my old bot work in the server

fast osprey
#

They "work"?

viral heart
#

Yeah, I have a /balance command for it and it worked

#

Now its not working idk how it did earlier but still showing

fast osprey
#

I mean code doesn't hang out in the air

viral heart
#

Problaly only showing on my end and I just have to deal with it until they eventually go away (hopefully)

fast osprey
#

There really isn't anything that just fades in time

viral heart
#

So I'm just gonna have to deal with it then

#

Atleast until I can figure out why its doing it

viral heart
#

Fixed it, I needed to go to intergrations and remove them

viral heart
#

2025-01-04 19:34:06 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected. how do i fix this because under privileged intents ive selected all of them and still get this warning

fast osprey
#

Not in code you haven't

viral heart
#

Yeah that would be true, didn't realize i had to do that

#

I've had it not give me that warning before though so I guess it was in there and i accedidently took it out

modest ether
#

hiring someone to make custom bots for meeee dm me please am paying good

lone reef
#

how to make a dc bot?

modest ether
lone reef
quartz wyvern
#

Hi is there anyone in voice?

fast osprey
modest ether
frail turtle
#

how to make a dc bot?
🙂
leaves

frank osprey
#

!rule9

#

!rule 9

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

short crater
#

someone I need help

#

it says "Nie mo" for EVERY command

#

any advices?

fast osprey
short crater
#

im just as clueless as you are

#

someone?

frank osprey
#

nie mo... niemo..... nemo

We found nemo folks someone give merlin and dory a call

frank osprey
short crater
#

i installed it

#

walk me through on what i could i have done wrong

#

@frank osprey

frank osprey
short crater
#

thats windows 11

#

the terminal is opened in visual studio code

frank osprey
#

pugsmirk oh the vs terminal... anyway give me a second

short crater
#

i even have the python extention installed

frank osprey
short crater
#

bro look

#

literally from the site

frank osprey
#

try just using

py -3 -m pip install -U discord.py

if you cant then you might need to start again

viral heart
#

I have a /staff-list command that auto pulls the owner and puts them in the owner category but I wanna be able to have my /staff-add command also give them a role that is the same as the category I put them in

#

For reference /staff-add <user><category> but I want to also have <role>

frail turtle
#

how to run a bot 24/7, I know you have to get a host but is there a good free alternative

fast osprey
#

No

#

These things cost money to run and people aren't running charities to run your stuff for you. There's always a catch

fast osprey
#

At least not something you can put users into

viral heart
frank osprey
#

so you want a command that give a role to someone?

fast osprey
#

Why not just roles?

viral heart
#

I am doing roles as well but I also want something that lists all my staff members

#

I'm getting it figured out though

fast osprey
#

So that could just be a role...?

frank osprey
#

yup

frail turtle
#

I have something similar like that

#

but instead listing roles

viral heart
#

Atleast I'm not the only one then, not neccessarly doing it the same but similar

frail turtle
#

You're doing it with embed?

viral heart
#

Yeah, look cleaner to me

frail turtle
#

that's true, I don't know why I haven't thought of that

#

lowkey will do the same

viral heart
#

Yeah, I did standard for a bit but figured out how to do the embed and thought it looked alot better

frail turtle
frank osprey
#

sorry to but in guys but,
help i dont get how this is not working, the dotenv is passing a improper token (im playing with cogs now)
im using py-cord not d.py

import os
from dotenv import load_dotenv

intents = discord.Intents.default()
intents.members = True
bot = discord.Bot(intents=intents)

load_dotenv("key.env")
TOKEN = str(os.getenv("DISCORD_TOKEN"))


@bot.event
async def on_ready():
    print("=-=-=-=-=-=-=-=-=-=-=")
    print(f"online as {bot.user}")
    print("=-=-=-=-=-=--=-=-=-=-")

bot.load_extension("cogs.testing")
# cogs_list = [
#    'testing'
# ]

# for cog in cogs_list:
#    bot.load_extension(f'cogs.{cog}')

bot.run(TOKEN)```
viral heart
#

Yeah I got no idea, I get alot of help from chatgpt and only know how to do a few things

fast osprey
#

What library and version are you running?

frank osprey
#

oh dam yeah py-cord v0.01

#

i didnt use chatgpt even oncepugsmirk

frail turtle
#

Made a somewhat complicated bot with that

fast osprey
#

and what makes you think the token is improper? Have you tried hardcoding it into your bot.run? Is there an error?

frank osprey
viral heart
fast osprey
#

Personally not a fan of .env for config when things like toml and yaml exist

frail turtle
viral heart
#

Dang, yeah my bots not gonna be that complicated

frank osprey
#

ah im just using .env cause thats just the first thing i seen to use

viral heart
frail turtle
fast osprey
#

for just a token .env is fine, but I couldn't tell you what you're doing wrong in there

#

are you putting " in?

viral heart
# frail turtle like game-ish?

Yeah, my trader bot will have a command to show where trader is in the game, prices, sellable prices, and game server info

frail turtle
#

oh that's cool

viral heart
#

and addon list/prices

frail turtle
#

I love how everyone got creative since chatgpt dropped

#

People who couldn't code (me) now are making a bunch of stuff

viral heart
#

Yeah, I started to learn how to code before I got into it but school got in the way. Chatgpt may not work well for it but it helps alot

fast osprey
#

chat gpt thinks 3 isn't a prime number sometimes. You shouldn't use it as a crutch

frank osprey
fast osprey
#

things will work until they don't, and then you're screwed because you chose not to actually learn what's happening

frail turtle
fast osprey
#

Again, it's not a problem until it is

frail turtle
#

right

fast osprey
#

and trust me, I've been around for a long time and people with your outlook never end well

frail turtle
#

I am doing this for fun

#

who cares

viral heart
frail turtle
#

I know the basics, couldn't be bothered to learn to code now along with already a bunch of stuff from college

#
  • other hobbies
viral heart
#

and the bots im making are only gonna be used until I can afford the bot I want then it'll be scrapped

frank osprey
#

"insert link to free courses you can do now"

fast osprey
#

I mean if you (and the people using what you make) understand the risks then go bonkers

viral heart
fast osprey
#

yeah the educational content out there varies wildly in quality

#

some is actually pretty good, just need to find someone you trust who can validate

frail turtle
#

99% of all guides on the internet are crap

#

You need to dig deep to find something that works.

viral heart
slate swan
frank osprey
#

Oh and just a update on my bot well i donno what i did but its working now ...
token is passing thru as .env

am i like tapping into some sort of magic?

fast osprey
#

Probably just didn't have it saved correctly or somethin

fast osprey
frank osprey
#

yeah probs

vapid parcel
#

how to pause invites in dpy?

vapid parcel
#

and disable dms in dpy

#

i dont see where I can pause invites and disable dms, I can only get information on it, unless I read the wrong thing.

viral heart
#

How would i fix this so my price list shows more than just the last 11 items

async def trader_prices_command(interaction: discord.Interaction):
    items = list(trader_prices.items())
    pages = [items[i:i + 25] for i in range(0, len(items), 25)]  # Paginate if needed
    for page in pages:
        embed = discord.Embed(title="Trader Prices", color=discord.Color.purple())
        for item, price in page:
            embed.add_field(name=item, value=price, inline=False)
    await interaction.response.send_message(embed=embed, ephemeral=True)```
slate swan
stark ingot
#

Do you start the bot with .run() or .start()?

slate swan
#

.run

stark ingot
#

Also you should be extra safe and reset your token and not put it directly in the code that you share. It is probably to small to obtain in that recording but it is better safe that sorry

#

can you add print statements before and after the run

slate swan
#

still not working

stark ingot
#

do both print statements run or only one of them?

#

or neither?

slate swan
#

neither

fast osprey
#

You're probably not running the code you think you are then

stark ingot
#

Can you make sure you are saving your code then try again?
If it still does not work can you post your full code without your token

slate swan
#
import discord
from discord.ext import commands
from discord import Intents



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


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


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


bot.run = ("insert_token")
stark ingot
#

Is that the code you are running as that is not the code in the video

slate swan
#

i opened it, but not the folder with it actually

#

so i had to open the folder with my discord bot code in vscode

stark ingot
#

But you have some commands in the video, there are not commands here and on_ready is different. I want to see the code that is in the c:Users/madma/Desktop/mnrsw bot/main.py file

slate swan
#

i had to rewrite the code

stark ingot
#

And you are still getting no output from the print statement before bot.run?

slate swan
#

yes

fast osprey
#

bot.run = ... is reassigning the method. It's not calling it

stark ingot
#

Can you put a print statement as the first line in the file

slate swan
#

like before the import?

stark ingot
#

yeah

#

Does that give output?

slate swan
stark ingot
#

just do a plain string like "test", you have not defined the bot object yet

slate swan
stark ingot
#

ok than what solstice said is the main issue. Functions need to have () after them in python to call them.
bot.run = ... is setting the function named run in the bot object to a new value. It is not running the function.
You need to pass your token as an argument to the run function like so bot.run("token")

slate swan
stark ingot
#

Yes you still have a =. That is the assignment operator meaning that you are assigning bot.run a new value not running the function.

slate swan
#

oh

#

i realized

#

thanks toot

fierce plaza
#

Hello! Can someone help me with my discord bot? Im using python and want to create a slash command such as /createchat, that creates a private Thread that only the user and the bot can see / message in

fast osprey
#

Which part are you having difficult with and which library are you using?

vapid parcel
#

whats the max time on these? In the discord client its 24 hours.

fierce plaza
fast osprey
#

!d discord.TextChannel.create_thread

unkempt canyonBOT
#

await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a thread in this text channel.

To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads) is needed instead.

New in version 2\.0\.
fast osprey
#

You can pass ChannelType.private_thread into type=

vapid parcel
fast osprey
#

Have you checked discord's api docs?

fierce plaza
fierce plaza
fast osprey
#

Also anyone with manage_threads perms on the channel

#

You would have to create the thread and then add this user to it

vapid parcel
#

really unorganized, and I am not seeing it.

fast osprey
#

Well they're the ones that control it, not the libraries

vapid parcel
#

Yeah I know that, but I was asking to see if anyone knew the limit.

#

Discord docs are the worst docs I have ever truly read imo.

fast osprey
#

From what I can see on the api it appears to just be a guild feature flag, not a time you pass in. Could look into the source of your library to see what it's doing

vapid parcel
fierce plaza
#

im getting the debug message saying it was created but sadly im not automatically being put into the thread

#

NVM! I got it. Thanks again for the help

fair shuttle
#

any1 know whats that?

drifting arrow
#

How come I cant load emojis from my json file? ;-;

drifting arrow
fair shuttle
earnest parcel
#

how do i setup python using command prompt to work on visual studio code?

drifting arrow
earnest parcel
#

?

drifting arrow
earnest parcel
#

on visual studio code

#

ik like for the bot im tryna make pip install discord.py

#

im a lil bit rusty

#

havent coded in a while

drifting arrow
#

Sure. But like, what have you attempted so far?

earnest parcel
drifting arrow
#

Have you made any attempts to install it yourself?

drifting arrow
earnest parcel
#

i need help installing it

drifting arrow
#

Installed using the EXE?

earnest parcel
#

i js need it to connect w cmd prompt

earnest parcel
drifting arrow
#

Restarted PC?

earnest parcel
earnest parcel
drifting arrow
#

Try restarting your PC

drifting arrow
fair shuttle
earnest parcel
#

js reset my pc n still getting ts

#

i wanna setup pip

viral heart
#

@earnest parcel python -m ensurepip --upgrade

tepid tree
#

hey does anyone know how to setup ⁠Modals for a discord bot like the popup thing

tepid tree
#

but does anyone know how to do it

#

like I can split profits I make off the discord bot

shrewd apex
shrewd apex
#

i just sent resources which display how to use modals

tepid tree
#

like I barley know how to code I just want someone to set it up for me and I can split profits

tepid tree
shrewd apex
#

not the right channel for this

tepid tree
#

which chanel

shrewd apex
#

not the right server for hiring either

#

we can help you program it, we won't do it for you

gusty flax
viral heart
#

Could anyone help me make a bot that sends a riddle daily and have them be random riddles that are good and don't repeat

shrewd apex
#

maybe check some public apis

viral heart
#

I got a bot done that I thought would do it but it just responds with Sorry, I couldn't fetch a riddle right now.

topaz stratus
topaz stratus
topaz stratus
viral heart
#

https://paste.pythondiscord.com/FWBA

def fetch_riddle():
    url = "https://www.riddles.com/difficult-riddles"
    response = requests.get(url)
    
    print(f"Response status code: {response.status_code}")  # Log the status code to see if there is an issue
    
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # Find the first riddle from the webpage
        riddle_div = soup.find('div', {'class': 'riddle-text'})  # Find the riddle text
        answer_div = soup.find('div', {'class': 'riddle-answer'})  # Find the answer text
        
        if riddle_div and answer_div:
            riddle = riddle_div.get_text(strip=True)
            answer = answer_div.get_text(strip=True)
            return riddle, answer
        else:
            return "Sorry, I couldn't fetch a riddle right now.", "No answer"
    else:
        return "Sorry, I couldn't fetch a riddle right now.", "No answer"
topaz stratus
#

this is why asher suggested free apis; you can't freely just scrape someone's website

viral heart
#

Dang, I don't know how to go about using an API for it