#discord-bots

1 messages · Page 396 of 1

fast osprey
#

Why not just make your responses ephemeral so you really shouldn't care where they run it?

slate swan
#

anyone know how to make your bot able to reply in DMS? after adding it as an "APP" no matter what i do i cant seem to get it to work like other bots can.

slate swan
amber tundra
#

did you add the allowed installs to the code?

amber tundra
# slate swan yeah..?

something like this:

@discord.app_commands.allowed_installs(guilds=True, users=True)
@discord.app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
slate swan
#

thanks that works

shrewd apex
#

no u need the relevant perms to view them

glad cradle
#

yes, but these permissions can be edited, they're just the default permissions

#

(e.g the owner can edit the permissions of the command to make it visible to everyone)

desert monolith
#

Okay so I've made slash commands on my bot for the very first time, my bot has the correct permissions in my server... It says in my terminal that the slash commands have synced, but when I go and try, it doesn't show up.... Have I missed anything?

stark ingot
#

There is no such thing as owner only permission, the highest is admin. You are probably talking about the bot owner check, which is something the bot does. This will not hide the commands. If you want commands that only specially you (the bot owner, and possibly any team members) can use you should make a guild command on a server you own and edit the permissions accordingly

stark ingot
desert monolith
#

omg thank you!

slate swan
#

hmm

#

takes me back

primal token
#

Real

frail coyote
#

**the embed looks like this **

Your hand: 8 (8)Dealer's hand:8 (8):
You win!

i want it to look like this

Your hand:8 (8)
Dealer's hand:8 (8)
You win!

**this is what the code looks like **

embed = discord.Embed(
title="Blackjack",
description=(
f"Your hand: {get_hand_string(player_hand)} ({player_value})"
f"Dealer's hand: {dealer_hand[0]} ?"
),
color=EMBED_COLOR
)

#

can anyone help me fix

#

also and tips on how to make my code better is always apricated

#

keep in mind its a discord embed and that could be why it looks like it should work but doesnt

stark ingot
#

\n is a new line character in python. You can put it in your string where you want it to go onto the next line. You could also use a multi line string that starts with 3 quotes """ or '''

#

!e

print("New\nLine")
print(
"""New
Line"""
)
unkempt canyonBOT
frail coyote
dapper cobalt
young dagger
#

How to block invisible/unclickable nicknames with automod?

fast osprey
#

You can use regex in a Block Words in Member Profile Names rule

young dagger
fast osprey
#

not terribly hard to make one

young dagger
#

The only one I could find was
^[\s\u200B-\u200F\uFEFF]+$

frail coyote
stark ingot
#

I told you what you need to do. Putting \n in a string is treated as a newline character. Or you can use a multi-line string that might feel more natural to you

frail coyote
stark ingot
#

You need to take out the quotes that are already there. For strings in python you can use """ or " you dont need both

frail coyote
#

its still changes orange

stark ingot
#

Yes, because you just added the """ around your existing code instead of changing the type of quotes around the strings

young dagger
#

Does anybody have a good regex to block invisible nicknames for Automod?

frail coyote
stark ingot
#

That would make 2 multi-line strings with one line each. This is because you start the string with f""" and then python will end the string when it sees """ next. So if you want it to be multiple lines you need to start with f""" and have the ending """ at the end of your entire string, not at the end of the line.

stark ingot
#

I do not know a good list of invisible charecters though

frail coyote
#

ok wb this

f"""Your hand: {get_hand_string(player_hand)} ({player_value})"
f"Dealer's hand: {dealer_hand[0]} ?"""

stark ingot
#

That will work, but there is still one small issue with it. You should be able to notice the small issue when you run the code and send the embed.

frail coyote
#

i see in the code

#

the f turned orange

young dagger
frail coyote
#

wait @stark ingot do i not need a f at all on the second line?

stark ingot
#

correct, as it is in a multiline string python just treats that as charecters in the string. You also dont need something in the first line

frail coyote
#

ok yes that worked

#

thank you for explaining it

vapid parcel
#

2024-12-11 22:37:34 WARNING discord.gateway WebSocket in shard ID None is ratelimited, waiting 59.37 seconds

chrome bear
#

is there a way in discord.py to create interactions on messages like this? (right click a message -> Apps) (in user installs ofc)

fast osprey
#

Those are context menus, you can make it via @bot.tree.context_menu. They get an interaction and a Message parameter

vapid parcel
unreal flare
#

im thinking of making an automatic review bot using python and a discord bot for offerup any tips

frail coyote
unreal flare
frail coyote
#

seems pretty difficult

stark ingot
# unreal flare im thinking of making an automatic review bot using python and a discord bot for...

The tip is, to not do this.

  1. Fake reviews are unethical.
  2. When people find out that your have fake reviews on your service (and they will eventually find out) your service will lose all credability. So it might work for a few customers but than your entire service will die.
  3. They way that you describe it it does not seem like you would be able to do this while also staying in-line with Discord TOS
    a. Specifically Discord Community Guidelines Number 21 and/or 22
    b. More explained here
timber dragon
#

Seems easy to do, I'm thinking something like the following:

  1. Monitor the member remove event for leaving users
  2. Check the Thread's members each time to see if only the bot is in it:
members = ...
# members[0] = first member in list 
if len(members) == 1 and members[0].id == <bot id (bot.user...)>:
    ...
  1. Delete the thread using the delete method
slate swan
timber dragon
keen oak
#

guys

#

why am i barbra streisand

#

anyway

#

is there anyway to get a webhook based on a discord bots id?

#

cuz there was this bot that scammed me

#

and i wanna get revenge

#

its based on a qr code

slate swan
slate swan
#

Would be a major issue for discord if you could randomly get webhook URLs

slate swan
keen oak
#

if i could then thats good cuz i can delete they're webhook

#

scammy webhook

slate swan
#

Imagine the kind of security vulnerability that would be..

timber dragon
#

You're pretty dumb if you scan random qr codes and get scammed by a discord bot lmao

opal vortex
#

If you scan a QR code you just asking for trouble

#

which is why I NEVER EVER DO IT

#

even when it's on the legit version of microsoft.com

#

😂

hasty pike
#

discord.Thread.message_count is returning 0 everytime

slate swan
#

It's an approximate count, just side note

wild needle
#

Hi

manic gull
#

hi guys

drifting arrow
#

Dont care who give it to you. Just dont scan it.

#

Bill gates offering you a trillion bucks to scan? Na it's a scam. Flee in terror

opal vortex
#

ye

vapid parcel
#

2024-12-14 01:22:35 WARNING discord.gateway WebSocket in shard ID None is ratelimited, waiting 59.27 seconds

Why is this happening with all of my Bots?

They aren't even on the same IP..?

finite salmon
#

is there anyway i can pass in a coroutine function to the check argument in discord.Client.wait_for ?
I'm doing a on_message event check in it and i need to some async api calls inside the check, but as far as i know i cannot pass in a coroutine to discord.Client.wait_for, so is there any work arounds for it?

#

pls ping me if you reply

teal delta
#

So you want to use Client.wait_for inside a check decorator?

finite salmon
teal delta
#

Not sure about that, good luck

finite salmon
#
def attachment_check(message: discord.Message) -> bool:
    try:
        fetched_msg = await thread.fetch_message(message.id) # This isnt possible since the function needs to be async...
    except discord.NotFound:
        fetched_msg = None

    return (
        message.author.id == author
        and len(message.attachments) > 0
        and message.channel.type == discord.ChannelType.private_thread
        and fetched_msg
    )

message = await interaction.client.wait_for("message", check=attachment_check)
#

basically this is the problem

#

either if there is some way for dpy to accept coroutines to the check or somehow run coroutines in a non async function (but that would lead to blocking)

vocal snow
fast osprey
#

also if you just want people to send you an attachment, you can make a slash command which accepts that as an input vs waiting for them to send it on a message

finite salmon
finite salmon
fast osprey
#

Why?

#

Sending a message and running a command require the same effort, the latter is just more guided and also sends it to the bot directly rather than anyone who can see the thread

#

But the info you need is on the message you already get. You get nothing more from fetching it again

fast osprey
#

...it is against tos

#

Which also is notably against this server's rules to help with

earnest ridge
#

yikes

#

im sorry then

fast osprey
#

nwnw. Just be careful as they've been cracking down more

finite salmon
#

and only after they send an attachment the bot replies with some details

finite salmon
#

im not storing any message data

fast osprey
#

It was in reply to a message that has since been deleted

finite salmon
#

oh okay

fast osprey
#

Up to you how you want to get that attachment, noting that waiting for a message is a) pretty confusing ux and b) requires you to maintain the message content intent

finite salmon
#

well its for a private bot in a particular server so the intent doesnt matter much

#

ill prob have to do it through a command ig

finite salmon
#

the data i need (the thread object) is only available for public threads

#

not private

fast osprey
#

Fetching isn't going to change any of that

finite salmon
#

im doing a different approach, i needed the thread object to check if the last message id sent in the thread is the same as the message id in the event, which confirms that the message has been sent in the correct channel

Since i cant do that, i fetch the message id from the thread to see if it exists there, if it doesn't means it isnt being sent in the correct channel, if it does exist mean it has sent to the correct channel

fast osprey
#

You're waiting for a message in the thread no? message in your code above is the message sent. message.thread isn't relevant here, message.channel is

fast osprey
#

You should probably be using pkgutil to automatically detect python modules instead of looping over the file system directly

#

That...that is a cog

fast osprey
#

It's also a bit unclear why you're trying to add this cog in both the init and the extension itself

#

That doesn't really address why you'd be trying to add a cog twice

#

That would definitely cause an error

#

I think you should decide how you want your extensions to behave firstly

#

Do you know what this __init__ is doing or how it accomplishes that plan?

#

But why is it and the individual modules both trying to add cogs to the bot

#

You need to decide when exactly you want these cogs added

#

And implement it there, and only there

finite salmon
# fast osprey You're waiting for a message _in_ the thread no? `message` in your code above is...

there are multiple threads being created in the same channel, and i need to check if the image is being sent in the correct thread with respect to the user, message.channel would be the same across all threads from the same channel, and that isnt what id want, i need to check if the message is being sent in the correct thread.

Normally id make my check like this..

def check(message: discord.Message) -> bool:
    return (
        message.author.id == author
        and len(message.attachments) > 0
        and message.channel.type == discord.ChannelType.private_thread
        and message.thread.id == thread.id  # message.thread is None here since it's private so it doesnt work
    )
fast osprey
#

Message.thread isn't what you want.

#

That describes the thread under the message. Which is never going to be populated for a message you just got

finite salmon
#

im not talking about message threads

#

im talking about channel threads

fast osprey
#

You're running a check on a message though

finite salmon
#

message sent in a channel thread

fast osprey
#

There is no need for you to fetch anything here

#

All of the information is in the objects you already have

finite salmon
#

then can you make the check for me

fast osprey
finite salmon
#

message.channel.id == thread.id ?

fast osprey
#

Or just direct compare

finite salmon
#

ill give it a shot

finite salmon
fast osprey
#

message.channel will be the Thread object if that message is in the Thread. It's a bit confusingly worded tbh

finite salmon
#

damn it does work

#

thanks man

rigid jacinth
#

hey i have a question

#

im getting a error thats telling me that. the username key doesnt exist

#

but i was just using the tool this morning and didnt change anything in the cod

#

code

fast osprey
#

Going to need the code and the error to speculate

rigid jacinth
#

ok

#

want me to send it to you in dms?

fast osprey
#

No, here is fine

rigid jacinth
#

i cant it just gets deleted

fast osprey
#

You can use a paste service

rigid jacinth
#

paste service?

#

ill paste it in here

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.

rigid jacinth
#

here

stark ingot
#

!rules
We wont help with that

unkempt canyonBOT
#

The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.

rigid jacinth
#

why not?

#

it just checks if a username is available its not bad?

stark ingot
#

Did you have to put your user token in a config file?

rigid jacinth
#

yes

stark ingot
#

Than it is against discord TOS

#

and therefore against this servers rules

rigid jacinth
#

most discord tools you have to put a token in?

stark ingot
#

You are only allowed to use the tokens of bots created through the discord developer portal. Anything that uses your discord token other than the offical unmodified discord client is against TOS

rigid jacinth
#

alr

stark ingot
#

This is stated in the documents your agreed to when creating a discord account. It is also shown in discord.com/robots.txt

rigid jacinth
#

arl

#

alr

hybrid tapir
#

how can i use multiple token's?

fast osprey
#

For what purpose? And where are the tokens coming from?

rigid jacinth
#

where do i get apis from

golden portal
#

what API?

candid vine
#

I want it to detect the person who changed the role moved but it does not put the right person.
it says the old person who changed the role of place

#
async def on_guild_role_update(before, after):
    global role_update_in_progress
    
    if role_update_in_progress:
        return
    role_update_in_progress = True

    
    message = f"Le rôle '{before.name}' a été modifié :\n"
    author = None

    # Vérifier si la position a changé
    if before.position != after.position:
        
        await asyncio.sleep(1)  

        
        async for entry in after.guild.audit_logs(limit=10, action=discord.AuditLogAction.role_update):
            
            if entry.target.id == after.id:
                author = entry.user  
                message += f"- Position changée de {before.position} à {after.position} par {author.name}\n"
                break  

    
    if before.color != after.color:
        message += f"- Couleur changée de #{before.color} à #{after.color}\n"

    
    if before.name != after.name:
        message += f"- Nom changé de '{before.name}' à '{after.name}'\n"

    
    if before.permissions != after.permissions:
        added_permissions = [perm for perm in after.permissions if perm not in before.permissions]
        removed_permissions = [perm for perm in before.permissions if perm not in after.permissions]
        
        if added_permissions:
            message += f"- Permissions ajoutées : {', '.join(str(perm) for perm in added_permissions)}\n"
        if removed_permissions:
            message += f"- Permissions retirées : {', '.join(str(perm) for perm in removed_permissions)}\n"

    
    if not author:
        message += "- Position inchangée.\n"

    
    channel = bot.get_channel(CHANNEL_ID)
    if channel:
        await channel.send(message)

    
    role_update_in_progress = False
fast osprey
#

It's not guaranteed the the audit log is updated within a second, nor that it's only updated once

candid vine
#

I don't understand

#

@fast osprey

fast osprey
#

Currently your code waits for a second and then checks the audit logs

#

The audit logs may not be updated within that second. They also may be updated multiple times

fast osprey
#

Not really, no. The audit log isn't particularly reliable. You can wait longer, and then put in some checks to make sure you get the record you want

timber dragon
#

Or use the auditlog event

candid vine
timber dragon
#

Check the .action against the discord.AuditLogAction you want to catch and check the docs of entry for what you need

candid vine
#

Ok

lost schooner
#

How do I remove 2 roles from a group of people who have a certain role.

fast osprey
#

role.members will give you the Members who have that role. On each of them you can call .remove_roles(...)

dry kelp
#

I do not say this as spoon feed, But here's a improved way of improving your code, take it as an example on how to keep building your codes 🙏

import discord
from discord.ext import commands
import asyncio


CHANNEL_ID = int

role_update_lock = asyncio.Lock()

@bot.event
async def on_guild_role_update(before: discord.Role, after: discord.Role) -> None:
    async with role_update_lock:
        message = f"Le rôle '{before.name}' a été modifié :\n"
        author: discord.Member | None = None

        # proper fetch for the audit to get the actor
        try:
            async for entry in after.guild.audit_logs(limit=5, action=discord.AuditLogAction.role_update):
                if entry.target.id == after.id and entry.created_at.timestamp() >= discord.utils.utcnow().timestamp() - 5:
                    author = entry.user
                    break
        except discord.Forbidden:
            message += "- Impossible de récupérer les logs d'audit (permissions insuffisantes).\n"

        # here, based off your code, you want to detect the changes
        if before.position != after.position:
            message += f"- Position changée de {before.position} à {after.position}"
            if author:
                message += f" par {author.name}"
            message += "\n"

        if before.color != after.color:
            message += f"- Couleur changée de {before.color} à {after.color}\n"

        if before.name != after.name:
            message += f"- Nom changé de '{before.name}' à '{after.name}'\n"

        if before.permissions != after.permissions:
            added_permissions = [perm for perm in after.permissions if perm not in before.permissions]
            removed_permissions = [perm for perm in before.permissions if perm not in after.permissions]
            if added_permissions:
                message += f"- Permissions ajoutées : {', '.join(str(perm) for perm in added_permissions)}\n"
            if removed_permissions:
                message += f"- Permissions retirées : {', '.join(str(perm) for perm in removed_permissions)}\n"
        
        # in case the actor was not found, we fallback
        # i used google translator for some text, hope i got it right
        if not author:
            message += "- Auteur inconnu pour cette modification.\n"

        # the bot will attempt to get the channel
        # if not found, message won't be sent, won't raise exceptions.
        channel = bot.get_channel(CHANNEL_ID)
        if channel:
            await channel.send(message)
fast osprey
#

audit logs are not populated immediately when an action happens

dry kelp
fast osprey
#

Dunno what you're paying discord to get instant audit logs all the time, but that ain't what anyone else experiences

dry kelp
#

😂

fast osprey
#

either that or your code is laggy enough to make up for it

dry kelp
#

Nope, the coded is actually well handled

#

I do not have any sort of problems

#

Security was tested, in a 100k members guild

fast osprey
#

I mean sure, but I'm telling you that discord does not do that instantly, nor do they claim to

dry kelp
#

Weird, punishment actions happens instantly 😂

#

and reversal right after punishment, and i do not delay it anywhere

fast osprey
#

oh this is "antinuke"

dry kelp
#

Correct

fast osprey
#

yikes

dry kelp
#

We actually made it quite nice, and i need to make anti raid too

#

big communities, big as 100k members, are asking for it

#

discord's automod, does not work, i personally use that in the development server, people joined, started spamming stickers

#

nothing happened

fast osprey
#

I would actively encourage people to not follow in your example but that's besides the point here. If you want to respond to information populated in the audit log, the proper way to do this is in the audit log event not in the action event itself

dry kelp
#

as example allowing a user doing certain actions for each protections in an amount of time

fast osprey
#

I'm not going to argue with you that these systems are actively harmful and are predicated upon people being too stupid to set up proper permissions on their server

dry kelp
#

So within this way, we can limit actions done by a user

#

based on the owner configuration

#

So, i don't think this is stupid, since it's helpful for the owner, he making bread 🤷‍♂️

fast osprey
#

A Role object has a .members property. That will be a list of Member

#

!d discord.Role.members

unkempt canyonBOT
thick plank
#

How do I access the discord.user.id from the discord.Interaction.user? The documentation says that it returns a Union[discord.User, discord.Member] but I haven't seen a Union in python before. Is access determined by indicies (similar to a list) ex. discord.Interaction.user[0].id?

shrewd apex
#

u will get user if command is ran in dms member if ran in server, both have id so u can just do for example interaction.user.id

thick plank
#

oh ok thanks

fast osprey
#

When the docs say a parameter is of type Union[X, Y] it means that parameter will either be an X or Y, depending on context

thick plank
#

That makes more sense

#

if str(interaction.user.id) in ["ID_1","ID_2"]: is what I'm doing

fast osprey
#

you don't need to cast it to a string to compare it, you could just leave it as an int on both sides

thick plank
#

I was just concerned about the size of the int

#

cause it's a stupid large number

fast osprey
#

strings take up far more memory

thick plank
#

Now that I think about it aren't python ints not restricted by architecture

#

Or is that a separate type for numbers over 64 bit

wanton current
#

you don't really have to worry about the size of an integer in python

fast osprey
thick plank
#

interesting

fast osprey
#

nice

#

The one confusion people run into is that discord limits the size of integer inputs on app commands, and snowflake ints are larger than that limit

wanton current
#

js moment

strong delta
#

I have extensive experience developing and deploying smart contracts using Solidity and integrating blockchain platforms like Ethereum and Binance Smart Chain. My expertise includes building decentralized applications (DApps) for DeFi protocols, token standards like ERC-20, ERC-721, and creating secure wallets. I’ve also worked on NFT marketplaces, including minting, trading, and metadata integration. I am proficient in cryptographic methods like hashing and key pair generation, ensuring secure blockchain implementations. My development toolkit includes Truffle, Hardhat, and APIs like Web3.js for efficient blockchain interaction. Additionally, I have hands-on experience with blockchain node deployment and data indexing using tools like The Graph.

slate swan
#

gross

slate swan
#

And it sounds like those average scams going around at the moment..

regal anchor
#

Traceback (most recent call last):
File "C:\Users\user\Desktop\TechnoServer\TechnoGuardian.py", line 1, in <module>
import discord
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord_init_.py", line 23, in <module>
from .client import *
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\client.py", line 51, in <module>
from .sku import SKU, Entitlement
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\sku.py", line 31, in <module>
from .app_commands import MissingApplicationID
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\app_commands_init_.py", line 12, in <module>
from .commands import *
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\app_commands\commands.py", line 53, in <module>
from .models import Choice
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\app_commands\models.py", line 44, in <module>
from ..member import Member
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\member.py", line 33, in <module>
import discord.abc
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\abc.py", line 59, in <module>
from .voice_client import VoiceClient, VoiceProtocol
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\voice_client.py", line 35, in <module>
from .player import AudioPlayer, AudioSource
File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\player.py", line 29, in <module>
import audioop
ModuleNotFoundError: No module named 'audioop'

slate swan
timber dragon
#

Or install audioop-lts

toxic notch
#

i cant find one in YouTube

fast osprey
#

youtube is not a good educational resource, especially not for this

#

You should refer to a library's official documentation

wanton current
plush thistle
shrewd apex
stark ingot
#

Note: All of the above is only if you are using discord.py. If you are already using a different library you need to use different resources.

young heart
#

I made a bot and used it only in two servers but it got hacked somehow. Can anyone tell me potential reasons behind it? I am 100% confident that I didn't leak the auth token

fast osprey
#

well I can tell you that they'd have an easier time finding a grain of rice on a beach than just guessing your token

wheat summit
#

How to make my bot that when that command is sent it deletes the message sent to use the command? Like this: (I made it manually).

#

Anyone?

wanton current
#

You can access that message with ctx.message depending on which library you're using.

wanton current
#

What's wrong

noble valve
wheat summit
noble valve
#

this should work as a minimal example for your repeat command assuming you're using dpy

wheat summit
stark ingot
wheat summit
fast osprey
#

same way you make any parameter to a python function optional, by adding a default

wheat summit
#

Ohh you mean like this? Value = ' '

glad cradle
wheat summit
wheat summit
#

(It's just one part of the code).

glad cradle
#
member: discord.Member | None = None
#

if you're using python 3.10 or higher

#

well the typehint doesn't matter anyway, the important part is the default value

#

you then need to handle the case where member is None in your code

wheat summit
#

It works! Thank you so much!

young dagger
sick birch
#

though you need a typehint so

glad cradle
#

you need a typehint but the union can be omitted iirc

odd pendant
#

when using commands.guild_only() is there an event called when a guild specific command is called outside of a guild?

fast osprey
#

!d discord.ext.commands.guild_only

unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).

If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only) decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
odd pendant
#

brilliant thank you

fast osprey
slate swan
#

I think something's been updated recently. I keep looking for slash command tutorials but they all refer to the old discord slash import. How can I find something more relevant?

slate swan
#

Thanks. It's hard to tell what to follow now.

finite salmon
#

Yeah lol

#

Don't follow yt vids usually, they get outdated pretty quickly

#

Guides and documents are more reliable because they can be easily editable to follow the latest version unlike videos

mild token
#

for pub/sub setup should i run api and bot within same script?

glad cradle
#

wdym with pub/sub?

slate swan
echo creek
#

Anyone know if it's possible to have a bot change a person's nickname based on two separate entries? Such as....

Bot: what is your game name?
User: Violet
Bot: what is your guild name?
User: The Lords

And the bot then changes the user's nickname to: [The Lords] Violet

fast osprey
#

Possible yes

odd pendant
#

are bots and members seperate entities now? As banning a member which is a bot raises MemberNotFound

stark ingot
#

That sounds like you are trying to ban a user app. If a user installs a user app it cannot be banned from the server (unless the app is also installed on the server but that wont change anything). If a user is breaking rules with a user app you should punish the user that ran the commands instead

fast osprey
#

What code are you using to do to that?

young dagger
young dagger
echo creek
fast osprey
#

A command would be ideal for discoverability and ease of use. Note that the bot will need the manage_nicknames permission to do so

scarlet aurora
#
    import discord
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord_init_.py", line 25, in <module>
    from .client import Client
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\client.py", line 33, in <module>
    import aiohttp
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp_init_.py", line 6, in <module>
    from .client import (
    ...<31 lines>...
    )
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp\client.py", line 35, in <module>
    from . import hdrs, http, payload
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp\http.py", line 7, in <module>
    from .http_parser import (
    ...<6 lines>...
    )
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp\http_pars  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp\http_parser.py", line 15, in <module>
PS C:\Users\dc\Desktop\zanco bot> py main.py
Traceback (most recent call last):
  File "C:\Users\dc\Desktop\zanco bot\main.py", line 1, in <module>
    import discord
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord_init_.py", line 25, in <module>
    from .client import Client
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\client.py", line 33, in <module>
    import aiohttp
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp_init_.py", line 6, in <module>
    from .client import (
    ...<31 lines>...
    )
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp\client.py", line 35, in <module>
    from . import hdrs, http, payload
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp\http.py", line 7, in <module>
    from .http_parser import (
    ...<6 lines>...
    )
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp\http_parser.py", line 15, in <module>
    from .helpers import NO_EXTENSIONS, BaseTimerContext
  File "C:\Users\dc\AppData\Local\Programs\Python\Python313\Lib\site-packages\aiohttp\helpers.py", line 6, in <module>
    import cgi
ModuleNotFoundError: No module na```I keep getting this
mild token
#

Else I need to keep pinging it at every 5 minutes always

peak granite
#

Do anyone know on how to make working ability for Ballsdex battle mode?

Example 1: If Ball B is on opponent's deck, Ball C will attack first.

Example 2: Ball A will heal itself if its health <20hp (ability can use twice)

shrewd apex
shrewd apex
bitter tundra
#

why discord.py doesn't log any error in the console?

mild token
#

The api updates randomly

slate swan
crude dagger
#

hey

peak granite
stark ingot
#

I don't but you are in a discord bot channel so you will probably have more luck asking in a different channel

viscid hornet
#

this is an interesting concept tbh

digital osprey
#

Is here a highend developer that could help me with something

#

if you are free and have time, please hit me up.

young dagger
peak granite
viscid hornet
viscid hornet
#

sounds pretty self explanatory

#

i'm in a class rn tho

peak granite
#

oh

#

I'm in my home

peak granite
#

Mine is WIB

viscid hornet
peak granite
stark ingot
# peak granite Do anyone know on how to make working ability for Ballsdex battle mode? Example...

Have you tried asking in either of the support servers linked on the GitHub? https://github.com/Ballsdex-Team/BallsDex-DiscordBot
Does ballsdex allow you to insert python code? Or are you trying to modify the code on the GitHub to make your own bot that is similar?

GitHub

Collect and exchange countryballs on Discord. Contribute to Ballsdex-Team/BallsDex-DiscordBot development by creating an account on GitHub.

peak granite
#

even the creator's himself wish if there is a tutorial

peak granite
viscid hornet
dapper cobalt
# peak granite Do anyone know on how to make working ability for Ballsdex battle mode? Example...

Assuming you're trying to modify the bot's functionality, then what you need to do is what you said in your message. Haven't seen the github source code, but I assume that 'Ball B' is a class that has a method that returns the deck it's on, so you can use that to check if ball_b.deck == player2.deck: ballc.attack() (it should be similar to this, this is not the actual code you're going to implement)

uncut hinge
#

Feel like this is a dumb question but Is it possible to run a script for a discord bot like daily auto messages without my PC being on?

fast osprey
#

There has to be some machine running to do something

#

whether it's your pc or a vps you rent

uncut hinge
#

Ahh so would have to host it on cloud.

slate swan
#

yep

#

like any other bot

uncut hinge
#

Newer to this stuff but catching on fairly quick. I may have to try my hosting service I use for websites. Only thing is I don't think it's a VPS. If not I shall grab one.

wheat summit
#

Reason of why this isn't working? ```py
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix= ".", intents= discord.Intents.all())
Guild = 1149794271935873126
@bot.command()
async def createRole(self, ctx, role: discord.role, guild = Guild):
await bot.create_role(ctx.author.server, name= role, permission= None)
await ctx.send("Created!")

@bot.event
async def on_ready():
print("Logged in as granata2012_23, with the bot Slushy Assistant. Ready to work.")

with open("token.txt") as file:
Token = file.read()

bot.run(Token)```

wheat summit
#

While role is there.

stark ingot
#

what discord bot library are you using? What command are you typing when you get the error?

slate swan
#

When you're executing the createRole command, it requires a role to be given as command argument

slate swan
#

You probably want to type hint to a str and not to a discord.role (not sure why lowercase as well, as it's not valid)

wheat summit
#

Nope not working.

stark ingot
#

It does not look like instances of commands.Bot have a create_role function.
Also, not sure why you have guild as an argument for the command when you could just get it from the context

wheat summit
stark ingot
#

Roles are attached to guilds not bots. So you would use a guild object

stark ingot
#

ctx.author.server additionally author does not have an attribute called server

wheat summit
stark ingot
wheat summit
stark ingot
#

In discord.py (and many other discord bot libs.) the first argument in your command function will be a Context object that has lots of information about the context of where/how the command was used. You can get the Guild object from the Context object and use the Guild object to create a role

Often people will abbreviate the context argument to ctx in their code. However in your code you have self as the first argument but your function is not in a class so the self argument is receiving the Context object and ctx is being treated as an argument to the discord command.

young dagger
#
# Role should be a string
async def createRole(ctx, role_name: str):
    # Use guild from the context object
    await ctx.guild.create_role(name=role_name)
#

You don't need to hardcode the guild ID if that is not something you really want to do

peak granite
polar plinth
#

does someone know what the rgb of the background from embeds is?

slate swan
#

Depends the theme
On the computer you can inspect element to know it

polar plinth
timber dragon
#

You can use discord.Colour.dark_embed() if using (a fork of) dpy

slate swan
#

Is it possible to do that in a command, it sends a embed to a channel option with content that u can write?

#

yes

slate swan
slate swan
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

low cape
#

!slash commands

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

static umbra
#

in telegram bot development, I have this error.
please help me.

:athletic_shoe::athletic_shoe:Bot is running...
ERROR:__main__:Critical error: This event loop is already running
An error occurred: This event loop is already running
f:\Project\3 Project\Telegram bot\main.py:155: RuntimeWarning: coroutine 'Application.shutdown' was never awaited    
  print(f"An error occurred: {e}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
f:\Project\3 Project\Telegram bot\main.py:155: RuntimeWarning: coroutine 'Application.initialize' was never awaited  
  print(f"An error occurred: {e}")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
wheat summit
#

Hello! I'm trying to make a channel be created in the category created in the command, but I have no idea of how to do it. Any ideas? py @bot.tree.command(name= "ally_create", description= "Creates an alliance!") async def ally_create(interaction: discord.Interaction, name: str): await interaction.guild.create_role(name= name) await interaction.guild.create_category(name= name) await interaction.guild.create_text_channel(name= name, category= ) await interaction.response.send_message("Alliance Created!")

viscid hornet
wheat summit
viscid hornet
#

you're missing a category object to go in the category kwarg

#

and i just told you where you would find that object

wheat summit
#

Ohh I see, sorry, doing it right now.

viscid hornet
#

!d discord.Guild.create_category

unkempt canyonBOT
#

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

Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel) except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.CategoryChannel) instead.

Note

The `category` parameter is not supported in this function since categories cannot have categories.

Changed in version 2\.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
indigo harbor
#

!d discord.Guild.create_category

unkempt canyonBOT
#

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

Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel) except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.CategoryChannel) instead.

Note

The `category` parameter is not supported in this function since categories cannot have categories.

Changed in version 2\.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
indigo harbor
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

mossy tundra
#

some requirements:

  • experienced with sqlite3
  • experienced in discord.py or nextcord
  • must have previous projects to show for it
    IF YOU FOLLOW THESE REQUIREMENTS PLEASE DM ME LOOKING FOR A BOT DEV
leaden olive
#

how can i make this button in this view work after bot restart?

bright wedge
#

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

slate swan
stark ingot
#

If you are not using discord.py dynamic items do not exist

wheat summit
#

How do I make alliance_name be defined in the on_submit function?py class AllianceModal(discord.ui.Modal, title= "Alliance Create"): alliance_name = discord.ui.TextInput(label= "Alliance Name:", placeholder= "Input your server name here.", required= True, min_length= 5, max_length= 20) async def on_submit(self, interaction: discord.Interaction): await interaction.guild.create_role(name= alliance_name) await interaction.user.add_roles(discord.utils.get(interaction.user.guild.roles, name= alliance_name)) new_category = await interaction.guild.create_category(name= alliance_name) await interaction.guild.create_text_channel(name= "discussion", category= new_category) await interaction.guild.create_text_channel(name= "annnouncement-requests", category= new_category) await interaction.guild.create_text_channel(name= "event-planning", category= new_category) await interaction.response.send_message("Alliance Created!")

fast osprey
#

It's a class attribute, you can access those through self.

wheat summit
fast osprey
#

No. Do you understand what self is in your on_submit?

wheat summit
fast osprey
#

It's the current instance of it yeah

#

So self has all of its attributes

#

self.x, self.y

wheat summit
fast osprey
#

Take a wild guess

wheat summit
fast osprey
#

Worth a try, if you understand what that means

wheat summit
fast osprey
#

What makes you think it's wrong?

wheat summit
#

self: alliance_name Also doesn't work.

#

@fast osprey What should I do then?

fast osprey
#

What are the errors

wheat summit
fast osprey
#

Well start sending em

wheat summit
fast osprey
#

That's not how parameters work

wheat summit
#

OHH WAIT.

#

I GOT CONFUSED.

fast osprey
#

The first parameter in an instance method should always be self, literally

wheat summit
#

Sorry it works.

#

I did it in the wrong place lol.

#

Yep everything checks out.

#

How am I being rate limited with manual syncing..

wheat summit
# fast osprey The first parameter in an instance method should always be self, literally

Also, when I click submit on my modal, it doesn't really do anything, any reason for this? ```py
class AllianceModal(discord.ui.Modal, title= "Alliance Create"):
alliance_name = discord.ui.TextInput(label= "Alliance Name:", placeholder= "Input your server name here.", required= True, min_length= 5, max_length= 20)
async def on_submit(self, interaction: discord.Interaction):

await interaction.guild.create_role(name= self.alliance_name)

await interaction.user.add_roles(discord.utils.get(interaction.user.guild.roles, name= self.alliance_name))

new_category = await interaction.guild.create_category(name= self.alliance_name)

await interaction.guild.create_text_channel(name= "discussion", category= new_category)
await interaction.guild.create_text_channel(name= "annnouncement-requests", category= new_category)
await interaction.guild.create_text_channel(name= "event-planning", category= new_category)

await interaction.response.send_message("Alliance Created!")

@bot.tree.command(name= "ally_create", description= "Creates an alliance!")
async def ally_create(interaction: discord.Interaction):
await interaction.response.send_modal(AllianceModal())```

fast osprey
#

That should error

wheat summit
fast osprey
#

Do you have logging enabled

wheat summit
fast osprey
#

Do you get normal outputs from the bot there

#

Because this absolutely would cause an error

wheat summit
#

What is the problem?

#

I also triend re-running it, but nothing.

fast osprey
#

Show what your terminal does output

wheat summit
#

Alright.

wheat summit
fast osprey
#

Okay it looks like you did enable logging. Do you have an error handler on the modal?

wheat summit
#

Is it the try: and except: command? If so, could you write it for me? I never used it before.

fast osprey
#

No no no, you shouldn't be using a try except here

#

Are the other things in the submit happening?

wheat summit
fast osprey
#

Send the full code of your modal, including indents, in a paste service

wheat summit
#
import discord
from discord.ext import commands

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

class AllianceModal(discord.ui.Modal, title= "Alliance Create"):
    alliance_name = discord.ui.TextInput(label= "Alliance Name:", placeholder= "Input your server name here.", required= True, min_length= 5, max_length= 20)
async def on_submit(self, interaction: discord.Interaction):
        await interaction.guild.create_role(name= self.alliance_name)

        await interaction.user.add_roles(discord.utils.get(interaction.user.guild.roles, name= self.alliance_name))

        new_category = await interaction.guild.create_category(name= self.alliance_name)

        await interaction.guild.create_text_channel(name= "discussion", category= new_category)
        await interaction.guild.create_text_channel(name= "annnouncement-requests", category= new_category)
        await interaction.guild.create_text_channel(name= "event-planning", category= new_category)

        await interaction.response.send_message("Alliance Created!", ephemeral= True)

@bot.tree.command(name= "ally_create", description= "Creates an alliance!")
async def ally_create(interaction: discord.Interaction):
    await interaction.response.send_modal(AllianceModal())

@bot.command()
async def sync(ctx):
   if ctx.author.id == 1109142957866619013:
        await bot.tree.sync()
        await ctx.send('Command Tree Synced!')
        print("Syncing Tree....")
   else:
        await ctx.send('You must be the owner to run this command!')
@bot.event
async def on_ready():
    print("Logged in as granata2012_23, with the bot Slushy Assistant. Ready to work.")

with open("token.txt") as file:
    Token = file.read()

bot.run(Token)```
fast osprey
#

In a paste service please, not discord

wheat summit
#

I'm stupid..

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.

wheat summit
#

I just figured out the error..

fast osprey
#

Is it not indented in the class?

wheat summit
fast osprey
#

Yup

wheat summit
#

How did I not saw that lol.

wheat summit
fast osprey
#

Which is?

wheat summit
fast osprey
#

What's the traceback

wheat summit
fast osprey
#

Nah I don't help in dms, easier for multiple people to chime in

wheat summit
#

@fast osprey ^^.

#

Wait.

#

@fast osprey Removed the files. Here. 2024-12-21 17:34:34 ERROR discord.ui.modal Ignoring exception in modal <AllianceModal timeout=None children=1>: Traceback (most recent call last): File Local\Programs\Python\Python312\Lib\site-packages\discord\ui\modal.py", line 189, in _scheduled_task await self.on_submit(interaction) File , line 9, in on_submit await interaction.guild.create_role(name= self.alliance_name) File Local\Programs\Python\Python312\Lib\site-packages\discord\guild.py", line 3533, in create_role data = await self._state.http.create_role(self.id, reason=reason, **fields) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 600, in request kwargs['data'] = utils._to_json(kwargs.pop('json')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File Local\Programs\Python\Python312\Lib\site-packages\discord\utils.py", line 651, in _to_json return json.dumps(obj, separators=(',', ':'), ensure_ascii=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File Local\Programs\Python\Python312\Lib\json\__init__.py", line 238, in dumps **kw).encode(obj) ^^^^^^^^^^^ File Local\Programs\Python\Python312\Lib\json\encoder.py", line 200, in encode chunks = self.iterencode(o, _one_shot=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File Local\Programs\Python\Python312\Lib\json\encoder.py", line 258, in iterencode return _iterencode(o, 0) ^^^^^^^^^^^^^^^^^ File Local\Programs\Python\Python312\Lib\json\encoder.py", line 180, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type TextInput is not JSON serializable

fast osprey
#

self.alliance_name is TextInput, not a string

wheat summit
#

Yes! It works!

wheat summit
wheat summit
#

But I got this error, it says that sync_permissions is not a valid argument in this code: ```py
class AllianceModal(discord.ui.Modal, title= "Alliance Create"):
alliance_name = discord.ui.TextInput(label= "Alliance Name:", placeholder= "Input your server name here.", required= True, min_length= 5, max_length= 20, style= discord.TextStyle.short)
async def on_submit(self, interaction: discord.Interaction):
role = await interaction.guild.create_role(name= str(self.alliance_name))

    await interaction.user.add_roles(discord.utils.get(interaction.user.guild.roles, name= str(self.alliance_name)))

    new_category = await interaction.guild.create_category(name= str(self.alliance_name))

    await interaction.guild.create_text_channel(name= "discussion", category= new_category, sync_permissions= True)
    await interaction.guild.create_text_channel(name= "annnouncement-requests", category= new_category, sync_permissions= True)
    await interaction.guild.create_text_channel(name= "event-planning", category= new_category, sync_permissions= True)
    new_category.set_permissions(role, read_messages= True, send_meessages = True, connect= True, speak= True)
    new_category.set_permissions(interaction.guild.default_role, read_messages= False, send_messages= False, connect= False, speak= False)

    await interaction.response.send_message("Alliance Created!")```
fast osprey
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel) for the guild.

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite) as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow\-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit) will be required to update the position of the channel in the channel list...
wheat summit
#

Oh..

wheat summit
fast osprey
#

Not accessed?

wheat summit
#

Code: ```py
class AllianceModal(discord.ui.Modal, title= "Alliance Create"):
alliance_name = discord.ui.TextInput(label= "Alliance Name:", placeholder= "Input your server name here.", required= True, min_length= 5, max_length= 20, style= discord.TextStyle.short)
async def on_submit(self, interaction: discord.Interaction):
role = await interaction.guild.create_role(name= str(self.alliance_name))

    await interaction.user.add_roles(discord.utils.get(interaction.user.guild.roles, name= str(self.alliance_name)))

    overwrites= {
        interaction.guild.default_role: discord.PermissionOverwrite(read_messages= False)
        role: discord.PermissionOverwrite(read_messages= True)
        }

    new_category = await interaction.guild.create_category(name= str(self.alliance_name))

    await interaction.guild.create_text_channel(name= "discussion", category= new_category)
    await interaction.guild.create_text_channel(name= "annnouncement-requests", category= new_category)
    await interaction.guild.create_text_channel(name= "event-planning", category= new_category)
    await interaction.response.send_message("Alliance Created!")```
fast osprey
#

Need to have commas between entries in a dictionary

#

{a:b, c:d}

wheat summit
#

Oh I see.

wheat summit
fast osprey
#

Something needs to run it

#

It won't just run in the thin air magically

wheat summit
fast osprey
#

Either run it yourself, or rent a machine that will do it

#

Commonly called vps (virtual private server)

wheat summit
fast osprey
#

You shouldn't expect someone to pay their money to host you (a rando)

wheat summit
#

Like this one: py main_guild= discord.Object.id(1293905755849887807)

fast osprey
#

that's not a guild, that's an Object

#

you can use bot.get_guild to get a Guild from an id

wheat summit
solid turtle
#

Where can I download python properly For windows

#

! help

#

!d help

unkempt canyonBOT
#

help()``````py

help(request)```
Invoke the built\-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help), it means that the parameters prior to the slash are positional\-only. For more info, see [the FAQ entry on positional\-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built\-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site) module.
midnight oracle
midnight oracle
low cape
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

honest quest
#

coded my first discord bot. Finally works perfect for the client -

cyan creek
#

so i got attachment
and am trying to send it with message

but discord.File(attachment.url) completly stops code from working

#

it just never passes

full lily
#

there's no error?

#

@cyan creek

teal delta
wanton current
#

For activities and status

shadow vigil
honest quest
#

anyone got any advice on how i can keep a good log for my information that gets stored on a json database?

its currently built into the folder but when t he bot restarts, itll clear the file of all saved data

fast osprey
#

"JSON database" is a bit of an oxymoron. JSON files aren't databases at all

#

You should use a proper database engine. SQLite is a good lightweight start

stark ingot
#

Solstice is right. But there are 2 things that could be causing your problem

  1. You are not actually saving the data ever you are just changes you make
  2. You are using replit or a similar service that does not allow you to save files that you change during run time.
toxic notch
#

Can you download Python on mobile so i can code a discord bot?

craggy haven
#
@commands.hybrid_command(
    name="purge", description="Delete a specific number of messages in a channel"
)
@app_commands.describe(amount="Number of messages to be deleted from chat")
@app_commands.describe(reason="Reason for purging messages")
@app_commands.checks.has_permissions(manage_messages=True)
async def purge(self, ctx, amount: int, reason: Optional[str]):
    if amount > 100:
        return await ctx.send(
            f"{amount} is too large, please keep it under 100.", ephemeral=True
        )
    elif amount < 1:
        return await ctx.send(
            f"{amount} is too small, please keep it above 0.", ephemeral=True
        )
    await ctx.channel.purge(limit=amount, reason=reason)
    await ctx.send(
        f"Purged {amount} messages from <#{ctx.channel.id}>.", ephemeral=True
    )
#

when i use a regular text command it replies and purges but when i use a slash command it purges but does send the message at the end

fast osprey
#

This should cause an error

craggy haven
fast osprey
#

Are you getting the error?

craggy haven
#

using a regular text command works but slash commands causes it to purge but not send a message

craggy haven
#

js in discord

fast osprey
#

You either have an error handler eating this error or you've disabled logging

craggy haven
#

i dont have an error handler

fast osprey
#

Are you getting any logs from the library?

craggy haven
#

sorry if im a bother im new to discord bots

fast osprey
#

You're probably using bot.start without enabling logging

#

Show how you're starting your bot in code

craggy haven
#
async def main():
    async with client:
        await load_extensions()
        await client.start(os.environ.get("TOKEN"))
fast osprey
#

Yeah you don't need this at all, you can replace whatever runs this with .run and put any setup in the bot's setup_hook. Also you shouldn't be calling this variable client if it contains a bot, those are two entirely different classes

#

Otherwise you'll need to setup logging yourself

craggy haven
#

i dont understand 😅

fast osprey
#

Which part?

craggy haven
#

thanks for the help <3

#

but like @fast osprey

#

it should work

#

i mean whats not working is the ctx.send and im sure its correct cuz ive used it in other functions

#

and purge is working even with the error

#

SUDDENLY IT WORKED @fast osprey

#

lmao

fast osprey
#

You should get the error first

#

This is causing an error

honest quest
# craggy haven lmao

if you have recently added a slash command, it can take a few minutes for it work as it needs to properly sync. You could potentionally add an event to your on_ready event in which will tell you that the commands are synced such as

@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
await bot.tree.sync()
print("Slash commands synced.")

#

this will then showcase in your terminal after you run python bot.py - that commands are synced and ready to go

fast osprey
#

You should not sync in on_ready, or pretty much anything

honest quest
#

why not?

fast osprey
#

and this isn't a syncing issue, otherwise the command wouldn't be available to run. It's a logic problem inside the command itself

#

!d discord.on_ready

unkempt canyonBOT
#

discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.

Warning

This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
fast osprey
#

read the warning in there

honest quest
#

ahhhh i gotcha

stark ingot
#

Additionally discord has a rate limit of 200 command syncs a day. So if you have 25 commands, you can only restart your bot a maximum of 8 times in a day

#

Which is bad if you are developing and changing a lot of things

fast osprey
#

Generally it's not recommended to automatically sync in any capacity; it is literally publishing an API and that should be a conscious decision

open cobalt
#

has anyone an idea if discord api can use long polling schema ? If not why, what are the disadvantages in this case?

fast osprey
#

That is decidedly not how the rest api works. You really aren't meant to poll the api at all, that's the entire point of having a connected gateway bot

open cobalt
#

I mean, like using just the rest api and have an endpoint for updates as a list/array, without any sockets, just requests. What is the problem with this schema? Why discord decied to have a websocket for updates and what are the disadvantages of long polling in this case?

fast osprey
#

That's the architecture they decided to go with...?

#

Or are you trying to reverse engineer that decision

open cobalt
#

Oh, sry for my questions!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Now I am angry thanI have ever been!!!!!!!!!!!!! gr!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

#

😠

fast osprey
#

"Long polling works great in situations when messages are rare.

If messages come very often, then the chart of requesting-receiving messages, painted above, becomes saw-like.

Every message is a separate request, supplied with headers, authentication overhead, and so on.

So, in this case, another method is preferred, such as Websocket or Server Sent Events."

open cobalt
#

I have asked the question because of telegram api that uses the schema of long polling!

fast osprey
#

I'm guessing the chose websockets because of the above, but we can only speculate

open cobalt
#

😠 sry for my questions!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!😠

#

😠

fast osprey
open cobalt
#

😂

shrewd apex
stark ingot
#

Pretty sure that it is for any modification or addition of commands

shrewd apex
#

only creating

#

not patches the docs state it

#
There is a global rate limit of 200 application command creates per day, per guild
viscid hornet
#

what the fuck

modern echo
#

Test test

slender perch
#

is it possible to make a discord bot that streams stuff?

fast osprey
#

Nope

toxic notch
#

How to code python in mobile??

cloud dawn
#

!d discord.app_commands.CommandTree.sync @candid briar

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

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

This must be called for the application commands to show up.
cloud dawn
#

Pass a guild id to only sync to that guild. Will be instant.

cloud dawn
#

Create a new tree and only add that command to the tree.

#

You can create multiple tree's yes

#

!d discord.app_commands.CommandTree

unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True, allowed_contexts=..., allowed_installs=...)```
Represents a container that holds application command information.
cloud dawn
#

Use this to create a new tree object then add a command and sync it to the specific guild.

#

@candid briar maybe you can also pass guild_ids in a cmd

#

!d discord.app_commands.Command

unkempt canyonBOT
#

class discord.app_commands.Command(*, name, description, callback, nsfw=False, parent=None, guild_ids=None, allowed_contexts=None, allowed_installs=None, auto_locale_strings=True, extras=...)```
A class that implements an application command.

These are usually not created manually, instead they are created using one of the following decorators:

• [`command()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.command)

• [`Group.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group.command)

• [`CommandTree.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.command)...
cloud dawn
#

It has a guild_ids arg maybe it will then only sync to that guild but I'm not too sure.

#

lowercase command is the decorator

#

Just guild then

#

!d discord.app_commands.CommandTree.command

unkempt canyonBOT
#

@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
low cape
#

!d

unkempt canyonBOT
low cape
#

! commands

#

!d commands

unkempt canyonBOT
#

commands [bpnumber]```
Specify a list of commands for breakpoint number *bpnumber*. The commands themselves appear on the following lines. Type a line containing just `end` to terminate the commands. An example:

```py
(Pdb) commands 1
(com) p some_variable
(com) end
(Pdb)
```  To remove all commands from a breakpoint, type `commands` and follow it immediately with `end`; that is, give no commands.

With no *bpnumber* argument, `commands` refers to the last breakpoint set...
slate swan
#

Anyone has a discord bot you can share? One with cogs, I am totally lost 😭

stark ingot
#

what discord bot library are you using? Most have an example with cogs on their github

slate swan
torn tusk
#

Has anyone ever had this issue before? Interaction gets handled in my code, no error but it keeps loading with the 3 dots on discords side for some reason? This loading can take up to a minute and blocks any other button/select menu

My connection is fine, and it only happens sometimes. Im thinking its got something to do with handling interactions in ephemeral messages, but im not sure.

fast osprey
#

Code?

sharp kernel
toxic notch
#

Also Can someone tell me how to reset the bots Tree commands

#

Tree?

#

Bruh

quick gust
honest quest
#

anyone know the rough specs a discord bot would need to run 99.99% of the time in 100+ discords?

quick gust
#

totally depends on what you're doing

tall olive
amber hatch
#

Tree?

vocal plover
# honest quest anyone know the rough specs a discord bot would need to run 99.99% of the time i...

How much heavy lifting is the + in 100+ doing here? Are we talking 105 servers or 7500 servers?
Are we running a music bot or something that just responds to app commands with static responses?

As long as you're talking about fairly small servers, let's say up to 2500 members, and you've got, let's say, 250 servers, and you're not doing heavy stuff like audio or image processing, then you can get away with fairly minimal resources. You could probably get away with 1GB of RAM and whatever specs of CPU you can find for that scenario, though I'd want more for a margin of error to grow into. You don't need some completely ridiculous overpowered box for the vast vast majority of bots. If you want a better answer, run your bot locally and see what it takes, then get a server that can handle that and a bit more, don't grow a ton before you need it.

honest quest
ancient lark
#

how to do a button like this

shrewd apex
#

make a link button

#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None, sku_id=None)```
Represents a UI button.

New in version 2\.0\.
prisma surge
#

How nice to have this bot source all from node.js

#

I mean python bot

orchid dome
#

Hi, im new on discord bots. Where i can learn more about library of discord with python?

slate swan
#

Pinned messages, channel description and the docs of the library you plan on using which can be easily found on the internet

stark ingot
#

Do note that discord.py is not the only option for python. You might want to look at the other libraries before making a decision. I have tried to get them to link or at least name some of the other libraries here but it never happened

vocal plover
#

Nextcord just released version 3 with some major updates, now is positively the best time to start using it 😉

open cobalt
vocal plover
#

It is possible I have some amount of involvement

stark ingot
young dagger
stark ingot
#

Personal preference, I dont know much about nextcordv3 but I imagine that there were quite a few structural changes to make things easier for the user

#
  • alec is a core dev there and they are cool
vocal plover
# young dagger What makes Nextcord special compared to discord.py?

(I'd make a terrible salesman) I don't think anything makes us particularly special, I think if your API wrapper is special you've probably done something wrong, but it has some structural differences, the main one I can pick off the top of my mind is that we do app commands much the same way text commands were done, rather than the command tree structure discord.py uses. I prefer that, but functionally both wrap the Discord API and let you build bots that do the same things, I'd argue nextcord (and disnake, and iirc pycord both do this the same as us) is the more ergonomic way to do app commands, but it really does come down to preference there

vocal plover
# stark ingot Personal preference, I dont know much about nextcordv3 but I imagine that there ...

v3 isn't hugely different structurally for users, we've just made a couple of breaking api changes which warrant a major version bump in accordance with semver, off the top of my head we've bumped the minimum python version from 3.8 to 3.12 to get everything that adds, changed how some async iterators work (i.e. channel.history()), and a bunch of stuff to do with how http requests are made internally, plus we've added more recent changes to the discord api in - those however are obviously expected changes and not the reason for the major version bump

stark ingot
#

got it, have you updated statuses on advaiths site yet?

vocal plover
#

I'll be honest I 100% forgor that advaith's site existed, I'll take a look and PR if someone else hasn't

wise gust
#

How do I fix this 😭

vernal bear
#

I have a feeling discord permissions won't let this work, but I thought I'd ask anyways. My idea is to create a self timeout bot (yes that is an unusual request i know). Essentially, I'd use a command to start a "timeout" for myself (not an actual timeout bc that would require server permissions) that would either delete any message i sent or block any messages from sending in the first place. however, i'm hoping to do it for a user-installed app so it wouldn't need any server permissions to do so. is this even possible? it would only be used on myself and would be unable to use on anybody else

viscid hornet
#

"module not found"

#

take a wild guess

viscid hornet
#

and what is this even for?

vernal bear
# viscid hornet > not an actual timeout because that would require server permissions > delete ...

yeah i figured that out. i was hoping user installed bots would have lesser permissions that would still allow me to do it but I don't think it's possible.

Essectially there are times when I really shouldn't be on discord (like now, I need to go to bed) so i just want something that will keep me from interacting without completely shutting down the app. Also, there are times when i'm in a bad mental state and don't want to say something reactively so I'd just rather eliminate the possibility altogether lol

viscid hornet
vernal bear
#

tyty im proud of it

viscid hornet
#

use a screen time limiter or smth

vernal bear
#

yeah i've tried those lol. all it takes is one click to bypass it and so it doesn't work for me

viscid hornet
#

discord obviously doesn't let you do this because think of all the ways you can exploit that, if it were a feature

#

"hey man check out my bot"

boom. prevented from speaking entirely

vernal bear
#

well the purpose of making it user installed would be so you can only use it on yourself, nobody else. idk if that makes sense

#

my solution right now is to have admins/mods put me in timeout but was hoping to find a way around that so i don't bother them. sadly i don't think i'll be able to do that

slate swan
#

axo

slate swan
quick gust
simple lagoon
#

Which is better File Or Dictionary For !balance

candid briar
fast osprey
#

What does that even mean

stark ingot
#

Database

wise gust
#

If someone could help me please

strange belfry
#

@wise gust is this your code or did you copy it

#

it dosent matter if you did at all I copy shi all the time i just think if you made the program a little more simple the debugging wont be as hard

wise gust
strange belfry
#

I understand what do you want the bot to do?

#

Like an auto role?

wise gust
#

It will give them a role

#

thats it

#

I use used_keys.json, keys.txt

strange belfry
#

I honestly hate using external files I always had errors I just always but all the shit in the same script it dosent look as pretty but that might resolve the issue

#

It always had problems locating the file

wise gust
#

I dont think its that, none of my commands are working/responding

strange belfry
#

Can you send me an invite to the server the bot is on

#

through DMs

stark ingot
strange belfry
#

I also realized you didn’t put the bots token in I’m pretty sure you need that for it to run

stark ingot
#

It may be because the bot does not have read message permission for the channel

strange belfry
#

In the discord portal make sure intents.messages = true are all turned in via the discords bot website

stark ingot
#

The message intent is not a privileged intent. And they would get an error if they tried using the message content intent without it turned on

strange belfry
#

oooooh alrighty

#

I’m a bit rusty I’ve been programming on my phone for the past year

stark ingot
#

Yeah, or you could print the message content

wise gust
strange belfry
#

@bot.event
async def on_command_error(ctx, error):
await ctx.send(f"An error occurred: {error}")

#

Throw that in there

stark ingot
#

You sent a message right? It sounds like your bot does not have the view message/channel permission

wise gust
#

It says worked but in reality the commands still aren't working

strange belfry
#

Isn’t your prefix !

wise gust
#

Oh my god.....

#

I forgot I set my prefix to !

strange belfry
#

Lmao

#

😂😂😂😂😂😂😂 it happens

wise gust
#

Thank you so much @strange belfry and can't forget @stark ingot I appreciate your guys help

strange belfry
#

of course make some cool stuff with that bot!

stark ingot
#

If you plan to expand this bot or make it public I do recommend you look at slash commands. They help you avoid problems like this

wise gust
stark ingot
#

What discord API library are you using?

wise gust
#

I know its @bot.tree.command()

#

Or something along those lines

#

And like discord.Interaction

stark ingot
wise gust
stark ingot
#

You would have to look at examples for the Roblox API. You can run whatever code you want in the command callback. So there is probably not an example of that specific case but you can combine multiple examples.

wise gust
#

https://paste.pythondiscord.com/5Y7A <-- This is my code, I'm trying to get my bot to check a Roblox users status to detect if there online or not, but its not working at all. Can someone help me?

brittle sage
#

has anyone encountered this recently? I reinstalled everything and still no luck. I've never had it come up before

wanton current
#

It's because python 3.13 removed the audioop module from the standard lib, you can fix this by installing audioop-lts (official solution) or by downgrading to python <3.13

brittle sage
vapid parcel
#

So im using nsfw=True in some of my sub commands. But say the parent doesn't have nsfw=true and the Sub of the parent has it, it doesn't work, is there a way around this to make it work without making 2 parents?

#

    parent_example = app_commands.Group(
        name="parent",
        description="example",
        guild_only=True,
    )

    sub_one = app_commands.Group(
        parent=parent_example,
        name="sub_one",
        description="example",
        nsfw=True,
    )

    sub_two = app_commands.Group(
        parent=parent_example,
        name="sub_two",
        description="example",
        nsfw=True,
    )

    sub_three = app_commands.Group(
        parent=parent_example,
        name="sub_three",
        description="example",
    )```
#

Sub 1 n sub 2 will have nsfw=True, but this doesn't work because the parent needs to have it.

#

but if I make the parent have it, then sub 3 will also have to be in nsfw channels.

wanton current
#

it does state this

vapid parcel
#

Yeah I knew that, but I was wondering if there was a way around it..?

#

not like around it, but another way of doing what im trying to do

sick birch
vapid parcel
#

thats what I was thinking so far, but didn't know if anyone else had any other suggestions

stark ingot
#

Subcommands are just treated as options so they can't have their own settings

wise gust
#
import discord 
import requests
from discord import app_commands, tasks


MY_GUILD = discord.Object(id=1322468323774038119) 

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):
        self.tree.copy_global_to(guild=MY_GUILD)
        await self.tree.sync(guild=MY_GUILD)

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

@client.event
async def on_ready():
    print(f'Logged in as {client.user} (ID: {client.user.id})')
    print('------')

def load_users():
    with open('users.txt', 'r') as file:
        return [line.strip() for line in file.readlines()]

def is_user_in_game(username):
    try:
        response = requests.get(f"https://api.roblox.com/users/get-by-username?username={username}")
        if response.status_code == 200:
            user_data = response.json()
            user_id = user_data.get("Id")
            if user_id:
                status_response = requests.get(f"https://www.roblox.com/home?rbxUserId={user_id}")
                return status_response.status_code == 200
    except Exception as e:
        print(f"Error checking user status: {e}")
    return False

@tasks.loop(seconds=60) 
async def check_users_in_game():
    users = load_users()
    for username in users:
        if is_user_in_game(username):
            channel = discord.utils.get(client.get_all_channels(), name='general')
            if channel:
                await channel.send(f"{username} is currently in a Roblox game!")

@client.tree.command()
async def hello(interaction: discord.Interaction):
    """Says hello!"""
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')```

My code^

The error: 
from discord import app_commands, tasks
ImportError: cannot import name 'tasks' from 'discord'
young dagger
wise gust
young dagger
wise gust
toxic notch
#

The fact that i ask questions and still no answers 😢

#

How do i reset my bots Tree commands

fast osprey
#

What are you trying to accomplish?

vapid parcel
simple lagoon
simple lagoon
#

Fuck you 😭

finite salmon
#

like pycord does those stuff for you automatically and so do some other wrappers

simple lagoon
finite salmon
#

fr same

smoky sinew
sturdy ibex
#

I’m trying to make tic-tac-toe with discord buttons but how do I use them?

stark ingot
#

What discord bot library are you using?

#

Or are you using the raw API?

smoky sinew
vapid parcel
#

Same goes for you lol

#

The whole point of that sync command is for YOU to build off of it. Not just use it like that. That is an example of a sync command.

#

and, what bot has just 1 command? You either have multiple commands + sub commands.

fast osprey
#

If they're saying a minor grammar mistake in a log makes something unusable, they're not arguing in good faith. Don't feed the troll

viscid hornet
#

they're UI elements - you attach them to a View

vapid parcel
fast osprey
#

That's what trolls do, they elicit reactions from people

vapid parcel
#

Goofy people 😭

vapid parcel
# sturdy ibex I’m trying to make tic-tac-toe with discord buttons but how do I use them?

You can visit an official one which is by Rapptz, or you can follow this other guide, I don't really know if its updated now, but you can try it.

GitHub

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

Gist

A gist which shows/tells you how to make buttons using discord.py v2(version 2.0.0a) - buttons.md

whole root
#

Yo

vapid parcel
#

1 is just examples, the other is just a guide with examples.

stark ingot
#

It could depend on what discord bot library they are using. It is not good to blindly recommend tutorials for discord.py

vapid parcel
#

I did forget abt that yes. That is my bad lol.

#

Those tutorials are for dpy. I forget abt other wrappers sometimes.

finite leaf
#

Yo wassup guys, i made a "discord bot" but that is not really a bot (used py autogui)
can somebody tell me how would i upgrade my code ?

#

its for spam btw

fast osprey
#

"It's for spam"

finite leaf
#

yeah and ?
How would i make it better

fast osprey
#

Maybe don't spam people, that would be better

finite leaf
#

nah its for test don't worry abt it

#

i am trying to get better at pyautogui so yeah this was my only idea of automated thing

fast osprey
#

Not hard to think of an idea that isn't obnoxious

finite leaf
#

ok but is it possible to make it better

fast osprey
#

Always is

finite leaf
#

? what you mean

fast osprey
#

Is this actually interacting with the discord client ui?

finite leaf
#

nah, it clicks on the text bar the it writes the text you wrote in the text_question input, then it sends the message by clicking enter, the while loop redoes the operation again and agin until you stop it

fast osprey
#

What text bar

finite leaf
#

The thing you are writing in right now

fast osprey
#

So exactly what I just said

#

That is against discord tos and by extension this server's rules

finite leaf
#

yeah but i dont use it its just to make myself betah in the pyautogui module

fast osprey
#

We don't help with things that break tos

#

And you claiming you won't use it doesnt change that

finite leaf
#

aight still thanks

frank osprey
#

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

finite leaf
#

aight

#

not gonna show the last file (.env, its the token)

#

btw i made it with a tutorial

#

so this one is good right ?

fast osprey
#

Not really sure what you're looking for

finite leaf
#

well is it good (good coding, aigainst comunity guidlines)

fast osprey
#

Your bot should not be messaging people who did not explicitly grant you consent to, no

#

This also just looks like it should be using commands rather than a bunch of chained if statements

finite leaf
#

aight thanks man

slim bloom
last cradle
#

and tuts for those bots that work in dms and group chats

stark ingot
#

They are called user apps
Do you have a library of choice? Most of the libraries have examples on the github repo

stark ingot
#

There are multiple python libraries though.
Py-cord, nextcord, disnake, discord.py, etc

stark ingot
#

Hmm, looks like they dont have an example for user apps. I dont use discord.py so you will have to wait for someone else. Sorry

strange belfry
fast osprey
#

Downgrade python or pip install audioop-lts

#

the newest version of python removed it from stdlib

frail coyote
#

if an error shows up like that it’s usually best to start with “pip install module name” in the terminal

strange belfry
#

i did start with that i didnt know i had to -lts it

low cape
viscid hornet
#

what am i reading

mint pecan
#

how can i get links inside of a message (if there is)

strange belfry
stark ingot
stark ingot
#

You could also check the message embeds I believe. This won't give you links that don't have an embed though

young dagger
#

I'm using discord.utils.utcnow() to save timestamps for infractions in my moderation bot. But when I run the command to display the timestamp in the logs using discord.utils.format_dt(), the timestamp appears an hour behind the actual time. What would be the optimal way to save timestamps so that they always display the accurate time, regardless of the machine or timezone the bot is running on?

polar plinth
#

any ideas why everytime a try to interact with the buttons there is "this interaction failed"?

fast osprey
#

Firstly this is really difficult to read. You shouldn't ever be in-lining callbacks and stapling them onto objects. You should subclass View and put your button callbacks in there

fast osprey
#

Huh

fast osprey
#

Which library are you using?

polar plinth
fast osprey
#

Anything in the examples/views folder in the repo

uncut bolt
#

Hi, my discord bot has just stopped being able to send embeds all of a sudden. Nothing has changed, none of my code has changed, this was all working last time I ran the command.

The relevant code snippet is:

        print("Creating embed for rules info...")
        embedVar = discord.Embed(title="Rules", description="description", color=0x00ff00)
        print("Adding field")
        embedVar.add_field(name="Strikes System", value="""Long Text""", inline=False)
        print("Sending embed...")
        await rules_channel.send(embed=embedVar)

It just stalls at line 2, it outputs no errors, and I can run other commands after it stalls. Just for some reason when it tries to create the embed it just doesn't. What's going wrong?

fast osprey
#

This code would never stall. If anything it would error

#

If you're not seeing that error, you should address that first

uncut bolt
#

How do I even go about addressing that?

fast osprey
#

Do you get any logs at all in your terminal from your library?

uncut bolt
#

No

fast osprey
#

You need to enable logging then

uncut bolt
#

ok

fast osprey
#

This differs between libraries. For discord.py this is usually people using bot.start() when they should be using bot.run() which sets up logging for you

open cobalt
#

hey guys, I know this is discord bots channel, but I have a quick review question. I am experimenting with the tele api. I have a thread running that executes a func that polls the events and returns it. then another func that process these events, is that a good start?

fast osprey
#

If you know this isn't the right channel why are you asking here lol

runic dawn
#

So i would need a discord bot that invities the user to a support server when authorized is there youtube tutorials or something?

fast osprey
stark ingot
open cobalt
#

youtube is a great knowledge ressource wtf

stark ingot
#

There is no reason to force add someone to your support server

fast osprey
#

You could also do this with the oauth join server scope but giving them an invite link is just as fine

runic dawn
#

Vanity link can be stolen you know that?

open cobalt
#

mhhh

fast osprey
#

"Stolen"?

#

The bot can also generate an invite link, not a vanity. Otherwise you're going to need to set up a whole oauth flow to do this

runic dawn
#

I cant just put a discord server link automaticly open in a browser

open cobalt
#

first of all, what is a vanity-link if someone can explain?

runic dawn
wanton current
open cobalt
#

I see, like a short cut for a url

runic dawn
open cobalt
#

ok, then I dont know

runic dawn
#

Is it against Discord TOS making a gambling bot?

#

And all currency will be earned whit tasks or other ways

open cobalt
#

maybe solsticeshard knows the answer, he should be familiar with the TOS of Discord

runic dawn
#

There is many discord gambling bots

#

Is it worth buying a rasberry pi for discord bot hosting

open cobalt
#

why not

#

it is a good choice

fast osprey
#

It's against tos if anything with real world value equivalency is being wagered or awarded

runic dawn
#

Is it even possible to install python on the rasberry pi pperating system

open cobalt
#

yes indeed it is possible

#

it is built up on debian linux i think

runic dawn
#

Oh nice

fast osprey
#

It entirely depends on what your bot does and what specs it needs

#

"Is this good for a discord bot" is about as vague as "is this good for a program"

runic dawn
#

Just a discord gambling bot

stark ingot
#

You need to make sure you get the correct modal though. Some dont have internet capabilities and some would not be powerful enough

open cobalt
#

with a database I assume

runic dawn
#

Is it risky if i use my home network?

open cobalt
#

mhhh good question, for self hosted websites I think for sure, but for a bot

#

we need an expert for that question

stark ingot
#

Not really, all the requests come from discord and you send to discord. The end user never directly "contacts" you

runic dawn
#

@rich hedge

runic dawn
#

Would i need a database for the discord bot for the balances etc?

open cobalt
#

the events are going through discod api and then to your bot to process it, the bot sends a request if you need to modify something to the api

runic dawn
open cobalt
#

everything is going through the discord api

runic dawn
#

I just want a yes or no

stark ingot
runic dawn
open cobalt
#

I am a big fan of mongodb despite like everyone in here is against it

fast osprey
#

No time like the present to learn

runic dawn
#

So if the discord bot shuts down the balances reset?

stark ingot
#

No-sql databases are very simple. Very similar to a python dict

open cobalt
#

yes that is true

#

like mongodb

runic dawn
#

I dont need a database tbh

stark ingot
runic dawn
open cobalt
#

if you want you can make a message event and everytime someone writes point += 1 or so

#

and then gamble with that points

#

small idea

runic dawn
#

Hmm

open cobalt
#

i dont know there are infinite ideas

#

be creative

runic dawn
#

Probably making games like crash towers mines doors limbo aviator

#

Cases

open cobalt
#

?

runic dawn
#

Is the gambling allowed if it uses virtual currency not real money?

open cobalt
#

i think yes, but maybe solsticeshard knows the answer

rich hedge
runic dawn
runic dawn
fast osprey
#

Crypto does have real world value lol that is absolutely gambling

runic dawn
open cobalt
#

bruh????????

runic dawn
#

But if i use robux?

open cobalt
#

😠

runic dawn
#

50robux=0.50$

fast osprey
#

If it could conceivably be traded for currency, it counts

#

It's also against Roblox tos to exchange robux

rich hedge
open cobalt
#

you know every companies tos he?

runic dawn