#discord-bots

1 messages ยท Page 343 of 1

frosty roost
#

How do you add animated server emojis to a message?

#

This is the code I use rn but it doesnt make it an animated emoji

#

Does work on statics tho

golden portal
#

<a:emoji_name:emoji_id>

vapid parcel
#

๐Ÿ˜ญ

copper bronze
#
@discord.ui.button(emoji=right_arrow, style=discord.ButtonStyle.blurple)
async def next(self, interaction: discord.Interaction, button: discord.Button):
        self.index += 1
        await self.edit_page(interaction)โ€Š

i have this button which is working but buttons are buffering and showing interaction failed Image 1
Image 2

golden portal
#

interaction failed means you didnt respond to the interaction

frosty roost
#

I have a /say command for the bot and im wanting you to be able to edit a message that has been sent by the bot how can I do this? Also is it possible to put that message into your typing bar so you don't have to retype the whole message?

fiery girder
#

how to i make a subgroup in app_commands.Group

naive briar
unkempt canyonBOT
#

class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.

These are usually inherited rather than created manually.

Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:

```py
from discord import app_commands

@app_commands.guild_only()
class MyGroup(app_commands.Group):
    pass
```...
fiery girder
#

so i do

class pokemon(Group):
 -----
class info(pokemon):
```??
fiery girder
#
info = Group(name="info", description="Get information about a pokemon")
play = Group(name="play", description="Play pokemon games")


class Pokemon(Cog):
    def __init__(self, bot):
        self.bot = bot
    
    pokemon = Group(name="pokemon", description="Pokemon commands", guild_only=True)
    
    pokemon.add_command(info)
#

but i still have all the info and play commands in the Cog

timid smelt
#
task = app_commands.Group(name="task", description="Task")
@task.command(name="set", description="Set task.")
#

@fiery girder Here's an example

#

It needs experience. Why not hire someone?

#
    def __init__(self, bot):
        self.bot = bot
    
    pokemon = app_commands.Group(name="pokemon", description="Pokemon commands", guild_only=True)
    
    @pokemon.command(name="info", description="Info")```
timid smelt
#

Message me I'll help

#

Yes

fiery girder
#

discord bot is simple

#

i mean i have over 9k lines of discord code on this single project

#

what you wannna learn

#

you want to make a simple moderation bot or game or etc you just need to be cretiive and know how to use the stuff you learn to make endless things

#

what boot

slate swan
#

is this still alive as it used to be

pale zenith
#

good question

timid smelt
#
    def __init__(self, bot):
        self.bot = bot
    
    pokemon = app_commands.Group(name="pokemon", description="Pokemon commands", guild_only=True)
    
    @pokemon.command(name="info", description="Info")
    async def info(self, interaction: Interaction):
    ...```
#

/pokemon info would be a command this way

silver pumice
unkempt canyonBOT
#

gary/__main__.py lines 18 to 22

COGS: list[str] = [
    dir.name[:-3]
    for dir in (resources.files(__package__) / "cogs").iterdir()
    if not dir.name.startswith("_") and dir.name.endswith(".py")
]```
silver pumice
unkempt canyonBOT
#

gary/__main__.py lines 47 to 52

if __name__ == "__main__":
    for cog in COGS:
        logger.info(f"[cyan]Loading the [bright_cyan]{cog.replace('_', ' ').title()}[/] cog...[/]")
        bot.load_extension(f"gary.cogs.{cog}")

    bot.run(getenv("TOKEN"))```
golden portal
#

that's fine, as long as you dont reinvent the wheel, you could also just use glob.glob for the same logic

silver pumice
mossy jacinth
#

im trying to add buttons to switch between embeds but i always get this error if i press a button:

Ignoring exception in view <IncidentView timeout=180.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='โ–ถ๏ธ' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\ui\view.py", line 375, in _scheduled_task
    await item.callback(interaction)
TypeError: next_page() takes 2 positional arguments but 3 were given

This is the whole code https://pastebin.com/SZ6HVspq

unkempt canyonBOT
#

bot/utils/exts.py lines 44 to 55

for module_info in pkgutil.walk_packages(module.__path__, f"{module.__name__}.", onerror=on_error):
    if ignore_module(module_info):
        # Ignore modules/packages that have a name starting with an underscore anywhere in their trees.
        continue

    if module_info.ispkg:
        imported = importlib.import_module(module_info.name)
        if not inspect.isfunction(getattr(imported, "setup", None)):
            # If it lacks a setup function, it's not an extension.
            continue

    modules.add(module_info.name)```
vagrant sable
#

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

desert kiln
#

hey people, I'm trying to make a music command for my bot, but when it is run, it keeps saying "Can't find file specified" I don't know why

shrewd fjord
#

Please provide code with more details

pliant briar
#

i want ask question,i want install discord.py and use app_command, but it always said

 ERROR: Could not find a version that satisfies the requirement discord.py==2.3.2 (from versions: 0.1.0, 0.2.0, 0.2.1, 0.3.0, 0.3.1, 0.4.0, 0.4.1, 0.5.0, 0.5.1, 0.6.0, 0.6.1, 0.6.2, 0.6.3, 0.7.0, 0.8.0, 0.9.0, 0.9.1, 0.9.2, 0.10.0, 0.11.0, 0.12.0, 0.13.0, 0.14.0, 0.14.1, 0.
14.2, 0.14.3, 0.15.0, 0.15.1, 0.16.0, 0.16.1, 0.16.2, 0.16.3, 0.16.4, 0.16.5, 0.16.6, 0.16.7, 0.16.8, 0.16.9, 0.16.10, 0.16.11, 0.16.12, 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.4.0, 1.4.1, 1.4.2, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.1, 1.7.2, 1.7.3)
#

what should i do then i can use app_command

golden portal
pliant briar
#

3.11.2

#

or maybe i stupid, because it only can do on 3.10?

golden portal
#

its 3.8+

#

it showing only up to discord.py==1.7.3 implies your python version is lower than 3.8

pliant briar
#

that's... interesting, but it does show is 3.11.2

golden portal
pliant briar
#

cmd

golden portal
#

well? is it pip?

pliant briar
#

yes use

pip install discord.py
golden portal
#

type pip --version

pliant briar
#

it pip (python 3.11)

golden portal
#

can you show me the whole thing instead of suppressing a lot of info, like i can't tell if you're in a venv, or system env

pliant briar
#

oh, i do it in venv

#

my bot.py

import os, discord, urllib.request
from dotenv import load_dotenv
from discord import Intents, Client, Message
from discord_slash import SlashCommand
from discord.ext import commands
from responses import get_response

#Step 1, load TOKEN from discordbot website
#Step 2 Set up
intents = discord.Intents.default()
intents.messages = True #NOQA, pls search yourself
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='/',help_command=None)
slash = SlashCommand(client, sync_commands=True)
guild_ids = ['myserverid']

#intents is gives permissions
#You Must set up Discord Client to here then you can operate the bot

#Step 3 Messages Functionality
async def on_ready():
    print(f'{client.user} is running now!')
    bot_status = discord.Game(name='Setting Bot, But You Can Talk With Me')
    #discord.Status, you can do -> online,offline,idle,invisible
    await client.change_presence(status=discord.Status.online, activity=bot_status)

async def send_message(message:Message, user_message:str):   
    if not user_message:
        print('(Message was empty because intents were not enabled probably)')
        return
    
    is_private = user_message[0] == '?'

    if is_private:
        user_message = user_message[1:]

    try:
        response: str = get_response(user_message)
        await message.reply(response) if is_private else await message.channel.send(response) 

    except Exception as e:
        print(e)

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

    username = str(message.author)
    user_message = str (message.content)
    channel = str(message.channel)

    print(f'[{channel}] {username}: "{user_message}" ')
    await send_message(message, user_message)

#Step 4 Main Entry Point
if __name__ == '__main__':
    load_dotenv()
    TOKEN = os.getenv('TOKEN')
    client.run(TOKEN)
    print(TOKEN)
#

and requirements.txt

aiosignal==1.2.0
async-timeout==3.0.1
attr==0.3.2
attrs==22.2.0
chardet==3.0.4
charset-normalizer==3.0.1
discord==1.7.3
discord-py-slash-command==3.0.3
discord.py==2.3.2
emoji==2.10.1
idna==3.6
multidict==4.5.0
python-dotenv==0.20.0
yarl==1.0.0
#

i install everything in venv,
pip install and do pip freeze > requirements.txt

#

all i want just build a basic bot, for fun

unkempt canyonBOT
shrewd apex
#

latest discord. py has slash command included already

pliant briar
#

ya i know it included but it just say it

 > [6/7] RUN pip install -r requirements.txt:
2.560 Collecting aiohttp==3.8.6
2.579   Downloading aiohttp-3.8.6-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (985 kB)
2.628 Collecting aiosignal==1.2.0
2.633   Downloading aiosignal-1.2.0-py3-none-any.whl (8.2 kB)
2.653 Collecting attr==0.3.2
2.661   Downloading attr-0.3.2-py2.py3-none-any.whl (3.3 kB)
2.704 Collecting attrs==22.2.0
2.708   Downloading attrs-22.2.0-py3-none-any.whl (60 kB)
2.735 Collecting chardet==3.0.4
2.741   Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB)
3.181 Collecting charset-normalizer==3.0.1
3.189   Downloading charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (162 kB)
3.218 Collecting discord==1.7.3
3.224   Downloading discord-1.7.3-py3-none-any.whl (1.1 kB)
3.287 Collecting discord-py-slash-command==3.0.3
3.293   Downloading discord_py_slash_command-3.0.3-py3-none-any.whl (45 kB)
3.346 ERROR: Could not find a version that satisfies the requirement discord.py==2.3.2 (from versions: 0.1.0, 0.2.0, 0.2.1, 0.3.0, 0.3.1, 0.4.0, 0.4.1, 0.5.0, 0.5.1, 0.6.0, 0.6.1, 0.6.2, 0.6.3, 0.7.0, 0.8.0, 0.9.0, 0.9.1, 0.9.2, 0.10.0, 0.11.0, 0.12.0, 0.13.0, 0.14.0, 0.14.1, 0.14.2, 0.14.3, 0.15.0, 0.15.1, 0.16.0, 0.16.1, 0.16.2, 0.16.3, 0.16.4, 0.16.5, 0.16.6, 0.16.7, 0.16.8, 0.16.9, 0.16.10, 0.16.11, 0.16.12, 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.4.0, 1.4.1, 1.4.2, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.1, 1.7.2, 1.7.3)
3.346 ERROR: No matching distribution found for discord.py==2.3.2
------
Error: failed to fetch an image or build from source: error building: failed to solve: executor failed running [/bin/sh -c pip install -r requirements.txt]: exit code: 1
#

it is i pretty confuse part, it only can found 1.7.3,

leaden jasper
#

:D

hushed galleon
#

does your requirements.txt have both discord==1.7.3 and discord.py==2.3.2? discord is a mirror of discord.py so you should only be installing one of them (if you're installing dpy 2.0 you should remove discord-py-slash-command as well)

pliant briar
#

oh ok w

#

so it mean if i install discord then discord.py is no need ?

shrewd apex
#

install manually your requirements.txt is outdated

pliant briar
#

oh bruh

silver pumice
golden portal
#

probably because its fairly fast to make one, ```py
for cog_path in glob.iglob(r'cogs/**/*.py', recursive=True):
cog_module = re.sub(r'\|/', '.', cog_path)[:-3]
await bot.load_extension(cog_module)

shrewd apex
silver pumice
#

which would completely break this

golden portal
#

how would it break?

#

and you're only using it in a cogs folder

#

oh the bots file as zipapps

shrewd fjord
silver pumice
shrewd fjord
fiery girder
#

like that

#

i alr know how too make it in hybrid commands but not in app i want to make it n app

#

it hybrid it goes like

@commands.hybrid_group()
async def pokemon:
 ----
@pokemon.group()
async def info
 -----
@info.command()
async def ability()
 -----
twilit whale
#

yo

#

i need help with modules

fiery girder
twilit whale
dry sparrow
#

i have this code

import discord.ext
from discord.ext import commands
import discord


TOKEN = "the_token_is_over_here"

client = commands.bot(command_prefix='!', intents=discord.Intents.all())

@client.event
async def on_ready():
    print("IT'S ALIVE!")
    
client.run(TOKEN)

when i run it i get this error

line 9, in <module>
    client = commands.bot(command_prefix='!', intents=discord.Intents.all())
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'module' object is not callable
#

what is happening?

dry sparrow
#

HELL NAW ๐Ÿ—ฃ๏ธ

#

thanks

dry sparrow
#

ok so here is the edited code


import hoodSong
import discord.ext
from discord.ext import commands
import discord


TOKEN = ":>"

client = commands.Bot(command_prefix="$", intents=discord.Intents.default())

@client.event
async def on_ready():
    print("IT'S ALIVE!")
    
@client.command()
async def hi(ctx):
    await ctx.send("hello!")
    

client.run(TOKEN)

but when i run $hi the bot isn't responding

slate swan
#
intents = ...
intents.message_content = True
winter coral
#

I have a list of names which are passed to bot.load_extension at startup. Now I would like a command to check whether each cog is loaded. How would I do that? bot.get_cog requires a different kind of name - I could maybe get away with Cog.__subclasses__(), but that is not exactly great.

#

[cls.__module__ for cls in bot.cogs.values()] does work

winter coral
fallen fable
#

anybody know how to do slash commands I have being trying to figure it out all day but there are so many different forms of it I am getting kinda frusturated

hushed galleon
#

generally they're not particularly difficult to write but it depends on what library you're using

#

discord.py is certainly in need of an official slash commands guide, but they're still working on it

fallen fable
#

right now im about to try discord-py-slash-commands

hushed galleon
#

that one is a few years out of date and isnt supposed to be used since dpy 2.0 released

fallen fable
#

alright uninstalling that then

hushed galleon
#

or rather the older version of discord-py-slash-command isn't meant to be used with dpy 2.0, however after 3.0.3 it turned into an outdated mirror for the author's rewritten, standalone package, interactions.py
(yes it's much more confusing than it should be, and unfortunately the author didn't add any deprecation warnings)

#

but anyway this third-party guide can help you out:
https://fallendeity.github.io/discord.py-masterclass/slash-commands/

or to summarize the basics:

  1. create a CommandTree (commands.Bot comes with one for free)
  2. define your slash commands using the tree (@bot.tree.command())
  3. synchronize your slash commands with discord some way, such as during login or with a command (bot.tree.sync())
bot = commands.Bot(command_prefix="!!!", intents=...)

@bot.tree.command()
async def hello(interaction: discord.Interaction):
    await interaction.response.send_message("Hello world!", ephemeral=True)
    await interaction.followup.send("This is a second message!", ephemeral=True)

@bot.event
async def setup_hook():
    await bot.tree.sync()  # Syncs global slash commands

bot.run(token)```
fallen fable
hushed galleon
#

that's a usual place to do it, personally i have a prefix command to manually sync when i need to

fiery girder
#

anyyone know how to make subgroups for groups and then commands for the subgroups using app_commands.group

#

i want it like /pokemon info ability

fiery girder
#

i get it nw why it was not working

#

i can only have one nesting

#

i had two in the pokemon

echo flame
#

Hello, Myself and a friend are trying to set up a new discord bot for a server and our experiencing an issues (paste bin of start to crash log https://pastebin.com/PCLXubpe) it keeps saying Failed building wheel for yarl and something about a file/directory named longinterpr.h not existing. Any help would be amazing.

fiery girder
#

something is wrong with the package or the service you are using its python version is outdated

echo flame
#

It is using Python 3.11.8

fiery girder
#

what r u using to make your bot

echo flame
#

As far as I am aware it was a premade bot by someone else and now we are just trying to actually get it hosted and online

fiery girder
#

try running it in your computer first

echo flame
#

And silly question... how would one do that?

fiery girder
#

you have python installed in your computer??

echo flame
#

I personally dont because I dont actually have the bot files

fiery girder
#

wait first where you got the code cause these might be a version mentioned

echo flame
#

Also unsure, as I said we was just given the files and asked to get it set up

fiery girder
#

well idk really then

#

just remove the package from the installing list

#

which is causing the problem

#

or just make a bot yourself

echo flame
#

I cant figure out which one it is, is the issue

#

I truthfully havent done Python in nearly 4 years. I have forgotten almost everything so sorry if im a little ya know

naive briar
# echo flame Hello, Myself and a friend are trying to set up a new discord bot for a server a...

This problem seems to have originated from the outdated Cython, try to update it with pip install Cython --upgrade if you can

GitHub

Describe the bug Because of python/cpython#28968, cython fixed it in cython/cython#4428 and is released with 0.29.5 To Reproduce pip install aiohttp Expected behavior To build the wheel. Logs/trace...

glad cradle
orchid mauve
#

hey

#

i have a discord bot with this code

   async def on_message(self, message):
        # we do not want the bot to reply to itself
        if message.author.id == self.user.id:
            return

        if "Heist" in message.content:
             await message.reply('<@&1210214496493371412>', mention_author=True)

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

now if i want to add a thing where
if 883086268450349116 is in the message then it cancels and doesnt send the ping
vague matrix
#

You want the message to be deleted?

shrewd apex
#

/a b c is max u can go iirc

#

u cant really invoke the group so its subcommand then command of subcommand group so just said it like 1 level

vapid parcel
#

You think this would be fine to keep in my on_ready?

    @commands.Cog.listener()
    async def on_ready(self):
        for guild in self.bot.guilds:
            try:
                self.invites[guild.id] = await guild.invites()
            except Exception as e:
                print(f"Failed to fetch invites for guild {guild.id}: {e}")```
vague matrix
#

Why would you want that in your on_ready?

#

Instead of another function

vapid parcel
#

Im asking would it be fine to keep there, if not then I can use another function aka setup_hook

meager rock
#

it won't work in setup_hook since bot.guids requires the cache to be loaded and it's empty before the bot starts
your ideal solution would be using a function with Bot.wait_until_ready function and then proceeding with the code

#

!d discord.Client.wait_until_ready

unkempt canyonBOT
#

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

Waits until the clientโ€™s internal cache is all ready.

Warning

Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.setup_hook) can lead to a deadlock.
vapid parcel
#

alr

#

ty

hushed galleon
#

in theory your bot might miss out on newly created invites if it were to be offline for an extended period of time, i.e. the point at which caches are cleared and on_ready is repeated, so if you care about being 100% up to date (or in other words you dont have any way to deal with a missing invite), i think on_ready is fine

vapid parcel
#

So you think on_ready will be fine with this whole process?

#

Ive been told to not put things in on_ready, but thats my only way of doing it right now. So thats why I came in here to ask.

#

I truly feel like it would be fine to leave this one in on_ready because its just cache n nothing else major imo

#

and when a invite is made or deleted it runs these 2 things, so the list is always updated when the bot is online.

    @commands.Cog.listener()
    async def on_invite_create(self, invite):
        if invite.guild.id in self.invites:
            self.invites[invite.guild.id].append(invite)
        else:
            self.invites[invite.guild.id] = [invite]

    @commands.Cog.listener()
    async def on_invite_delete(self, invite):
        if invite.guild.id in self.invites:
            self.invites[invite.guild.id] = [i for i in self.invites[invite.guild.id] if i.code != invite.code]
hushed galleon
vapid parcel
#

Well by that then, I will keep it in on_ready. I think I should be fine too tbh. I have no thought of it being bad I guess lol

hushed galleon
#

plus i believe they hold references to their guild which will stop receiving updates after on_ready evicts them from the cache, so you might experience sutble issues like outdated/inconsistent data if you happen to use the guild attr from the invite

hushed galleon
vapid parcel
hushed galleon
#

does the command that enables invite tracking also fetch the guild's invites when needed? good place to check if the bot has perms too

vapid parcel
#

alr, I will have to do that

#

I can just make it check to see if enabled.

#

it will always get all invites tho when a new member joins if the feature is enabled, then check to see what changed n stuff like that from the new_invites

#

so it kinda does have a check for that already, but now I just have to make sure the bot has perms

hushed galleon
vapid parcel
hushed galleon
#

im not sure how the bot would know which invite was used from just the new invites...

vapid parcel
#

it will see which one gained a new use

#

let me double check tho to see if im correct

#

You are correct, but I can just handle it to where it wouldn't know the invite code. Which would be fine I think.

#
                        else:
                            log_embed = discord.Embed(
                                title="Member Joined",
                                description=f"{member.mention} has joined the server, but I couldn't determine which invite they used.",
                                timestamp=discord.utils.utcnow(),
                                color=config.main_color
                            )
                            log_embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
                            log_embed.add_field(name="User ID", value=member.id, inline=False)
                            log_embed.add_field(name="Account Created",
                                                value=f"{discord.utils.format_dt(member.created_at, style='R')} / {discord.utils.format_dt(member.created_at, style='f')}",
                                                inline=False)
                            log_embed.add_field(name="Server Joined",
                                                value=f"{discord.utils.format_dt(member.joined_at, style='R')} / {discord.utils.format_dt(member.joined_at, style='f')}",
                                                inline=False)

                            await webhook.send(embed=log_embed)```
hushed galleon
#

it might be worth mapping the invite code to the uses rather than storing invite objects directly, since you'll need to manually update the count after a member joins anyway

vapid parcel
#

you just fetch the uses of that code

#
        self.uses: Optional[int] = data.get('uses')
hushed galleon
#

discord doesnt tell you which invite was used when a member joins so dpy has no way of automatically updating its uses, which is kinda why invite tracking is annoyingly complicated

vapid parcel
hushed galleon
#

thats what i mean by updating the counts, otherwise old_invites will be out of date

vapid parcel
#

it compares the old invites with new invites, if the new invite has 1 use above old invite code, it assumes it used that invite code, but if it can't determine, it will look for if vanity url, still if no vanity url, it will determine it can't find which code it used, so then it will just send an embed without tracking details n say they joined, n show the user data.

hushed galleon
hushed galleon
vapid parcel
hushed galleon
vapid parcel
hushed galleon
vapid parcel
#

oh no

vapid parcel
#

now at the bottom it will do

self.invites[member.guild.id] = new_invites

#

So then it will update the old invites with the new invites it fetched.

#

So it always has an updated invite list for that exact guild.

mighty pilot
#

Has anyone built a voice to text bot in python? I found scripty which is open source so I could use it but it's not built with python

vapid parcel
glad cradle
slate swan
#

hey guys new to coding discord bots , how can i raise the timeout before it just says "the application didnt respond" ? my code takes a bit to complete

shrewd apex
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
mossy jacinth
#

hey im trying to make a poll command with buttons for people to vote with but it gives me an error:

Ignoring exception in view <poll timeout=180.0 children=5> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='test' emoji=None row=None>:
Traceback (most recent call last):
  File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\ui\view.py", line 371, in _scheduled_task
    allow = await self.interaction_check(interaction)
  File "c:\Users\blaul\Desktop\admin helper\main.py", line 2039, in interaction_check
    return interaction.user == self.user
AttributeError: 'poll' object has no attribute 'user'

I even tried asking chat gpt but it didnt help at all... It only tried destroying the code like usual

class poll(nextcord.ui.View):
    def __init__(self, options, message):
        super().__init__()
        self.options = options
        self.message = message

    async def on_button_click(self, button, interaction):
        self.clear_items()
        for option in self.options:
            if button.label == option:
                await interaction.response.send_message(f'You voted for {option}!', ephemeral=True)
                break

    async def interaction_check(self, interaction):
        return interaction.user == self.user

@bot.slash_command(name="poll", description="Create a poll with buttons")
async def poll(ctx, question: str, option1: str, option2: str, option3: str = None, option4: str = None, option5: str = None):
    options = [option for option in (option1, option2, option3, option4, option5) if option is not None]
    if len(options) < 2 or len(options) > 5:
        await ctx.send("Please provide between 2 to 5 options for the poll.")
        return

    embed = nextcord.Embed(title="Poll", description=question, color=nextcord.Color.blue())
    for i, option in enumerate(options):
        embed.add_field(name=f"Option {i+1}", value=option, inline=False)

    view = poll(options, ctx.message)
    for option in options:
        view.add_item(nextcord.ui.Button(style=nextcord.ButtonStyle.primary, label=option))

    await ctx.send(embed=embed, view=view)```
north kiln
#

pass the user object as an attribute of the view

mossy jacinth
#

well now that error is gone and i think i did it correctly but the buttons dont send a the message...

class Poll(nextcord.ui.View):
    def __init__(self, options, user):
        super().__init__()
        self.options = options
        self.user = user

    async def on_button_click(self, button, interaction):
        self.clear_items()
        for option in self.options:
            if button.label == option:
                await interaction.response.send_message(f'You voted for {option}!', ephemeral=True)
                break

    async def interaction_check(self, interaction):
        return interaction.user == self.user

@bot.slash_command(name="poll", description="Create a poll with buttons")
async def create_poll(ctx, question: str, option1: str, option2: str, option3: str = None, option4: str = None, option5: str = None):
    options = [option for option in (option1, option2, option3, option4, option5) if option is not None]
    if len(options) < 2 or len(options) > 5:
        await ctx.send("Please provide between 2 to 5 options for the poll.")
        return

    embed = nextcord.Embed(title="Poll", description=question, color=nextcord.Color.blue())
    for i, option in enumerate(options):
        embed.add_field(name=f"Option {i+1}", value=option, inline=False)

    view = Poll(options, ctx.user)

    for option in options:
        view.add_item(nextcord.ui.Button(style=nextcord.ButtonStyle.primary, label=option))

    await ctx.send(embed=embed, view=view)```
north kiln
#

don't think on_button_click exists as an event

#

you should add that function as a callback of the button itself

mossy jacinth
#

thanks

scenic pike
#

In this Discord.py tutorial, we'll learn how to implement a Mute command using Discord's Python library. Muting users can be a crucial feature for managing voice channels effectively, especially in larger servers. By following along with this step-by-step guide, you'll understand how to code a Mute command using Discord.py's Cog.

๐Ÿ”ดSubscribe t...

โ–ถ Play video
naive briar
#

Me when there's the built-in /timeout command

quick gust
naive briar
#

Gotta love that random red arrow

long pecan
#

Hey!
How do I make something in the likes of:

async def cmd(...):
    """description which will be default for the help for this command"""
    if not var:
         await send aboves default help function here

Or is this something that is done automatically by discord when not all vars are provided?

hushed galleon
long pecan
#

This is prefix command. (for now anyway)

hushed galleon
#

in that case, dpy raises a MissingRequiredArgument exception which you can catch in an error handler and send a message based on what was missing

#

!d discord.ext.commands.MissingRequiredArgument

unkempt canyonBOT
#

exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter that is required is not encountered.

This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.UserInputError)
long pecan
#

I'd like to access the default help for the command. which should be created by the docstring.

hushed galleon
#

then you can pass the command object contained in that exception the context to ctx.send_help()

long pecan
#

And what is the command object?
I'm using cogs.

    @commands.command(name="cmd")
    async def cmd(self, ctx: commands.Context, *, message: str | None) -> None:
        if not message:
             ctx.send_help() # just this?
hushed galleon
#

ctx.command refers to the Command instance that the context is invoking, that being cmd in that example

long pecan
#

okay.
so
ctx.send_help(ctx.command) would do the trick? ๐Ÿ™‚
(testing now)

hushed galleon
#

personally i would still suggest using an error handler if you need to do this for multiple commands so you dont need to repeat the same conditions

#

dont forget to await it too

#

fyi it can be as simple as: py @commands.Cog.listener() async def on_command_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send_help(ctx.command) else: raise error # show other error messages in terminal

long pecan
hushed galleon
unkempt canyonBOT
#

discord/ext/commands/help.py lines 1221 to 1222

if self.show_parameter_descriptions:
    self.add_command_arguments(command)```
slate swan
#

also when making custom help command this might be helpful

#

!customhelp

unkempt canyonBOT
#
Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

long pecan
#

Thanks!

slate swan
hushed galleon
unkempt canyonBOT
#

discord/ext/commands/core.py lines 643 to 650

try:
    if cog is not None:
        local = Cog._get_overridden_method(cog.cog_command_error)
        if local is not None:
            wrapped = wrap_callback(local)
            await wrapped(ctx, error)
finally:
    ctx.bot.dispatch('command_error', ctx, error)```
slate swan
#

hmm let me try it out just for curiosity

hushed galleon
# slate swan hmm let me try it out just for curiosity

this is what i got ```py
import discord
from discord.ext import commands

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

@bot.event
async def on_command_error(ctx, error):
raise

@bot.command()
async def hello(ctx, name):
await ctx.send(f"Hello {name}!")

bot.run(...)
py
Traceback (most recent call last):
File ".venv\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "test.py", line 8, in on_command_error
raise
RuntimeError: No active exception to reraise```

#

in theory it should work for the local and cog handler, but im too lazy to test that

#

curiously that try/finally block doesnt include execution of the local handler, so i guess the event never gets dispatched if the local handler fails?

slate swan
glad marsh
#

Error: ```raceback (most recent call last):
File "main.py", line 41, in <module>
bot.load_extension(f'cogs.{filename[:-3]}')
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/disnake/ext/commands/common_bot_base.py", line 523, in load_extension
self._load_from_module_spec(spec, name)
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/disnake/ext/commands/common_bot_base.py", line 455, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.utility_commands' raised an error: NameError: name 'bot' is not defined


Code: ```py
intents = discord.Intents.all()
bot = commands.Bot(
    command_prefix='?',
    intents=intents,
    case_insensitive=True
)
bot.remove_command("help")

# Load Cogs
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        bot.load_extension(f'cogs.{filename[:-3]}')

Library - Disnake

Can anyone help?

slate swan
glad marsh
# slate swan the error is from a file that you didnt show
# Import Disnakes
import disnake as discord
import disnake
from disnake import Webhook
from disnake.ext import commands, tasks

# .env Imports
from dotenv import load_dotenv
import os

# psutil
import psutil # STATS

# Default Imports
import toml # EVAL
import textwrap # EVAL
import traceback # EVAL
import asyncio
from datetime import datetime
import datetime # Days Commands
import time # STATS

# DB
import aiosqlite

# Functions
from functions import *

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


def setup(bot):
    bot.add_cog(utility_commands_cog(bot))```
slate swan
#

well from this code i can see it shouldnt raise that error

#

so you are not showing something or its wrong file

muted trout
#

can anyone help me private?

slate swan
muted trout
# slate swan why not here?

because i m German and idk how to say it so i will create a Bot with Python but the bot wouldnt go online and idk why

slate swan
muted trout
#

Ok wait

#

import discord
from discord.ext import commands
import os

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

@bot.command()
async def ping(ctx):
await ctx.send('pong')

my_secret = os.environ['DISCORD_TOKEN']

#

all what i got now

slate swan
#

you need to actually start the bot using bot.run(token)

muted trout
#

Doesnt work

#

Can i write you private and share my screen?

slate swan
#

nope

muted trout
#

Mh ok then what i shpuld do now?

slate swan
muted trout
#

yeah its an error wait

#

Traceback (most recent call last):
File "/home/runner/DCE/main.py", line 13, in <module>
bot.run(token)
NameError: name 'token' is not defined. Did you mean: 'open'?

slate swan
#

๐Ÿคฆโ€โ™‚๏ธ

#

the token was just a placeholder for you actual token

muted trout
#

but if i write the Token there anyone can see it

slate swan
#

who said you have to write it here

muted trout
#

where should i?

slate swan
#

in your code?

muted trout
#

yeah but anyone can see the code

slate swan
#

but you are already using environment variables

#

you literally have the token in a variable already

#

just need to pass it to bot.run()

muted trout
#

ah ok

#

nope doenst work

slate swan
#

.. what doesnt work? what did you do

muted trout
#

import discord
from discord.ext import commands
import os

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

@bot.command()
async def ping(ctx):
await ctx.send('pong')

bot.run()

#

i write exact this but it doesnt work

slate swan
#

you have a variable my_secret that has a token
and you have to put it inside bot.run()

muted trout
#

bot.run(my_secret) ?

slate swan
#

try

muted trout
#

nope the same error

slate swan
#

what error

muted trout
#

Traceback (most recent call last):
File "/home/runner/DCE/main.py", line 13, in <module>
bot.run(my_secret)
NameError: name 'my_secret' is not defined

slate swan
muted trout
#

yeah but then you say i didnt have to write the last part

slate swan
#

i dont remember saying that

muted trout
#

so i have to make the first code?

#

or what did you mean

slate swan
#

just put back that variable

muted trout
#

done and now?

slate swan
#

try to run it?

muted trout
#

Traceback (most recent call last):
File "/home/runner/DCE/main.py", line 13, in <module>
bot.run = os.environ['my_secret']
File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/os.py", line 680, in getitem
raise KeyError(key) from None
KeyError: 'my_secret'

slate swan
#

i dont know from where did you get bot.run = os.environ but yeah i would recommend learning python before making a bot

#

cause you clearly have no idea what you are doing sorry.

muted trout
#

funny the bot is offline

#

and i m learning yeah youre right

#

but it doenst work

viral mica
#

import pyttsx3
import speech_recognition as sr

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices[0].id)
engine.setProperty('voices', voices[0].id)

def speak(audio):
engine.say(audio)
print(audio)
engine.runAndWait()

def takecommand():
r = sr.Recognizer()
with sr.Microphone(device_index=0) as source:
print("listening....")
r.pause_threshold = 1
audio = r.listen(source,timeout=1,phrase_time_limit=5)

    try:
        print("Recognizing...")
        query = r.recognize_google_cloud(audio, language='en-in')
        print(f"user said:  {query}")

    except Exception as e:
        speak("say that again please...")
        return "none"
return query

if name == "main":
takecommand()
speak("This is advanced jarvis")

#

"C:\Program Files\Python312\python.exe" C:\Users\vvish\PycharmProjects\pythonProject\jarvis.py
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0
listening....
Traceback (most recent call last):
File "C:\Users\vvish\PycharmProjects\pythonProject\jarvis.py", line 21, in takecommand
audio = r.listen(source,timeout=1,phrase_time_limit=5)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\vvish\AppData\Roaming\Python\Python312\site-packages\speech_recognition_init_.py", line 465, in listen
assert source.stream is not None, "Audio source must be entered before listening, see documentation for AudioSource; are you using source outside of a with statement?"
AssertionError: Audio source must be entered before listening, see documentation for AudioSource; are you using source outside of a with statement?

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "jarvis.py", line 35, in <module>
takecommand()
File "jarvis.py", line 18, in takecommand
with sr.Microphone(device_index=0) as source:
File "AppData\Roaming\Python\Python312\site-packages\speech_recognition_init_.py", line 189, in exit
self.stream.close()
^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'close'

Process finished with exit code 1

flat solstice
#

Can you grab a channel using get_channel or fetch_channel from the command context?

@commands.hybrid_command(name="suggestion-approve", description="Approve a suggestion created by the community")
    async def suggestapprove(self, ctx: Context, suggestionid: str):
        channel = bot.get_guild(1208279263438966875).get_channel(1211381701561942108)
        message = await channel.fetch_message(result[4])
        await message.edit(embed=embed)

The above code genrates the below error

Command 'suggestion-approve' raised an exception: AttributeError: 'NoneType' object has no attribute 'get_channel'

I can't remeber if it either of the below is possible

channel = ctx.get_channel(1211381701561942108)
channel = ctx.get_guild(1208279263438966875).get_channel(1211381701561942108)
slate swan
#

if you want to access the guild or channel the command was invoked in you can use ctx.guild or ctx.channel

leaden olive
#

can someone help me

slate swan
#

guild is None

tender knoll
#

can someone help me fix this?

slate swan
#

send full traceback here as text

tender knoll
#

nevermind its just that my wifi was down

#

wait no its back down:

slate swan
#

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

tender knoll
slate swan
#

try this but i doubt this is the case

tender knoll
#

thanks

#

what is that ssl certificate it's telling me to download?

slate swan
tender knoll
#

hold on a sec, I have an idea for how else to fix the problem

#

I'll be back in a few minutes

#

I fixed it I think, I just had to connect my laptop to ethernet because for some reason its Wifi turns off when I close the screen and my discord bot script was running while the screen was off

#

oop, no nevermind

tender knoll
#

this isn't strictly related to python but does anybody know how to make my laptop's wifi stop turning off when I close the screen?

small gyro
#

Google it would be your best go to

mossy jacinth
#

I don't even know what to say

small gyro
#

Try this

#
intents = discord.Intents.default()
intents.members = True
intents.message_content = True```
#

@mossy jacinth

slate swan
#

he already has .all() enabled

mossy jacinth
#

i dont know if i did something wrong in the code

slate swan
#

you dont pass intents ?

mossy jacinth
#

bruh i somehow moved that down there ๐Ÿ˜ญ

#

i think i selected it and accidentally dragged it

#

like this maybe but i hope thats the issue ๐Ÿ˜ญ

#

another question ๐Ÿ˜ญ is there a way to send a message instead of showing "The application did not respond"?

slate swan
#

use await interaction.response.send_message()

tender knoll
slate swan
#

why i can't get message from server callback pls help

small gyro
#

Use them

slate swan
#

wdym

stone gate
#

what are the limits of discord.User, discord.Role and discord.Channel?

like for example, am i able to only display the roles a user has, or a channel within a specific category, or is it limited to all the channels a user is able to see and all roles?

#

for interaction obviously

glad cradle
river plank
#

with the use of pil or smthing

shrewd apex
#

original image + tint image

#

you would do this multiple times cycling through colours and store the frames to create a gif

river plank
#

oh right

#

do you think you could give an example

shrewd apex
#

perhaps once I get back home

river plank
#

thanks

cloud dawn
#

I wanna see this shiba

shrewd apex
long pecan
#

Dont you hate it, but love it at the same time, that you figure out the answer yourself while trying to formulate a proper question..?

quick gust
#

that's possible?

#

crazy

rugged shadow
long pecan
#

Yeah it's great!

long pecan
#

Im looking for someone to talk me through syncing commands to discord. If someone has some time..?
There are a couple of opinions about this topic. Some with a synced flag in the setup_hook. I've decided I dont want to do this and I made a command to "manually" sync the commands only when I have to.
Now that my bot is only in 1 guild there;s no real reason to sync globally as far as I understand how that works anyway. So I've made a command for it in a Cog which does this.
synced = await self.bot.tree.sync(guild = ctx.guild)
According to online you can then return len(synced) to see how many commands are synced, however it's always 0 and it doesnt seem to actually give me the commands in discord?

Im trying to sync to guild only as i've heard it's faster than global..?

pale zenith
#

And yeah, you generally should not auto-sync.

long pecan
#

do I do:
self.bot.tree.copy_global_to(guild)
then:
synced = await self.bot.tree.sync(guild = ctx.guild)
?

pale zenith
#

yes. But then again, I do think it's better to sync globally since there's no difference

long pecan
#

Okay, so how would I sync globally?

pale zenith
#

Not passing guild=... To sync

long pecan
#

right xD

pale zenith
#

:P

long pecan
#

And in your XP, how long does it take for discord to reflect changes?
I've read "up to an hour" for global commands.
Which was the reason why I looked into syncing to guild only as it's supposed to be quicker?

pale zenith
#

Instant. It doesn't take up to an hour anymore,

Addressing that last statement. It is a misconception from a time when it was true, when slash commands were released, a couple of years ago.

long pecan
#

Okay. Then still im doing something wrong I think.

#

Oeh!
I got it! ๐Ÿ˜„

#

guild = ctx.guild self.bot.tree.copy_global_to(guild = guild) synced = await self.bot.tree.sync(guild = guild)
Works a charm to load to guild in any case.
Like you said, instant!

#

Thank you so much! Been getting headaches about this for a long time. ๐Ÿ™‚

pale zenith
#

No problem

long pecan
#

Back to testing. ๐Ÿซก

pale zenith
#

๐Ÿซก

shrewd vapor
#

Hi guys, can someone help me correct this error that sometimes occurs

2024-02-22 21:03:41 ERROR    discord.client Ignoring exception in on_member_update
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/listen.py", line 147, in on_member_update
    row = connect_db(guild_id, "SELECT channel_id FROM log_moderation WHERE guild_id = %s;")
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/cogs/listen.py", line 13, in connect_db
    cursor.close()
  File "/home/container/.local/lib/python3.11/site-packages/mysql/connector/cursor_cext.py", line 541, in close
    self._cnx.handle_unread_result()
  File "/home/container/.local/lib/python3.11/site-packages/mysql/connector/connection_cext.py", line 990, in handle_unread_result
    raise InternalError("Unread result found")
mysql.connector.errors.InternalError: Unread result found```
#
@commands.Cog.listener()
    async def on_member_update(self, before, after):
        guild_id = before.guild.id
        row = connect_db(guild_id, "SELECT channel_id FROM log_moderation WHERE guild_id = %s;")
        if row is None:
            return
        channel_id = row[0]
        channel_send = before.guild.get_channel(channel_id)
        if len(before.roles) < len(after.roles):
            newRole = next(role for role in after.roles if role not in before.roles)
            if before.roles != after.roles:
                logs = [log async for log in after.guild.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update)]
                logs = logs[0]
                embed = discord.Embed(title = f"Member roles updated", description = f"{before.mention} Member updated", color=discord.Color.dark_purple())
                embed.add_field(name = "Role added :", value = newRole.mention, inline=False)
                embed.add_field(name = "Modified by:", value = logs.user.mention, inline=False)
                embed.add_field(name = "Account created :", value = before.created_at.strftime('%d %B %Y at %H:%M (UTC +0)'))
                await channel_send.send(embed=embed)
        elif len(before.roles) > len(after.roles):
            oldRole = next(role for role in before.roles if role not in after.roles)
            if before.roles != after.roles:
                logs = [log async for log in before.guild.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update)]
                logs = logs[0]
                embed = discord.Embed(title = f"Member roles updated", description = f"{before.mention} Member updated", color=discord.Color.dark_purple())
                embed.add_field(name = "Role removed :", value = oldRole.mention, inline=False)
                embed.add_field(name="Modified by:", value = logs.user.mention, inline = False)
                embed.add_field(name = "Account created :", value = before.created_at.strftime('%d %B %Y at %H:%M (UTC +0)'))
                await channel_send.send(embed=embed)
#
def connect_db(guild_id, query):
    connection = mysql.connector.connect(host='', database='', user='', password='')
    cursor = connection.cursor()
    cursor.execute(query, (guild_id,))
    result = cursor.fetchone()
    cursor.close()
    connection.close()
    return result```
vale wing
shrewd vapor
#

ok, i go to try with a waiting queue for execute request

vale wing
#

What

#

You're killing entire point of async

shrewd vapor
#

My bot is on a multi server so he create a lot of request to the db

vale wing
#

Yes and you are handling them in a crazy inefficient way

shrewd vapor
#

So i need to connect to the database only when i start the bot ?

vale wing
vale wing
#

And store it as attribute of bot subclass

shrewd vapor
#

But if the bot doesn't send any queries to the database for a while, won't that break the connection ?

vale wing
#

Then close in Bot.close() override

vale wing
#

If your db wrapper supports pools it's better to use them however

#

But still one pool per app

shrewd vapor
#

i use MySQL

vale wing
#

Quick googling

#

It operates same way as connection except it creates connections for you as they are needed

vapid kestrel
#

anyone able to help me make it so my webhook sends messages, it only gives me a output in VSC


import requests
import time

WEBHOOK_URL = "no"

def send_discord_message(message):
    payload = {
        "content": message
    }
    headers = {
        "Content-Type": "application/json"
    }
    response = requests.post(WEBHOOK_URL, json=payload, headers=headers)
    if response.status_code == 204:
        print("Webhook message sent successfully.")
    else:
        print("Failed to send webhook message. Status code:", response.status_code)

def check_username_availability(username):
    url = f"https://auth.roblox.com/v1/usernames/validate?birthday=1970-01-01T00:00:00.000Z&context=UsernameValidationContext&username={username}"
    response = requests.get(url)
    data = response.json()
    if data.get("valid") == False:
        send_discord_message(f"Taken: {username} is taken on Roblox.")
    elif data.get("valid") == True:
        send_discord_message(f"@everyone {username} is available!")
    elif data.get("error"):
        if data["error"]["message"] == "Inappropriate":
            send_discord_message(f"Inappropriate: {username} is not appropriate for Roblox.")
    else:
        print("Unexpected response:", data)

def main():
    username = "nopnref"
    while True:
        check_username_availability(username)
        time.sleep(0.01)

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

also, dont take the username nopnref i want webhook to send msg if valid

whole flint
#

Hello, I am a beginner and am currently looking for a better hoster than Replit, can someone help me?

whole flint
shrewd vapor
tough trail
#

hi guys, what databases u are using?

sick birch
#

SQLite is good if you want something more lightweight

split vessel
serene fjord
#

anyone know how to get a users default avatar if they don't have one

avatar = user.avatar.url if user.avatar else f"https://cdn.discordapp.com/embed/avatars/{int(user.discriminator) % 5}.png"
#

I thought it all relied on a user id

split vessel
#

works for default avatars

#

avatar = user.display_avatar.url no need for other endpoints urls

pale zenith
latent jay
#

How can I get all messages from a channel?

#

I remember there's a way to do it with list comp

latent jay
#

Not sure if I'm doing it wrong.

history = [message.content async for message in channel.history()]
print(len(history))
# always only printing 100
#

Do I have to append the messages to a seperate list and iterate by chunks

serene fjord
#

I forgot the error but decided to try a work around

#

but thx @split vessel @pale zenith

split vessel
golden portal
latent jay
naive briar
#

Show your current code

golden portal
#

yea what the cat said

#

cos i cant repo

latent jay
# naive briar Show your current code
async def extract(interaction: discord.Interaction, channel: discord.TextChannel) -> None:
    if channel is not None:
        history = [message.content async for message in channel.history(limit=None)]
        print(len(history))
    else:
        await interaction.response.send_message("**Ensure you specify a channel!**")
storm abyss
#

That free?

#

Nice

split vessel
#

Buddy he is asking for a "hoster" not an editor

storm abyss
#

Is that hoster or editor?

whole flint
#

Link?

storm abyss
#

That

split vessel
cloud dawn
rocky geyser
#

Guys! I encountered a problem. My code doesnt mention anything about 'help' command.. But still upon calling it, it works

#

Like this. I just wanted to know if this a default behaviour of discord package

north kiln
#

it is the built in help command

rocky geyser
#

How to disable it?

north kiln
#

pass help_command=None to your bot

rocky geyser
#

where?

cloud dawn
rocky geyser
#

I didn't get it.. Should I attach my code file?

cloud dawn
#

You need to pass the help_command kwarg in the Bot constructor.

north kiln
#

somewhere in the file there should be

_ = commands.Bot(...., help_command=None)
rocky geyser
#

ok ic

#

with intents right?

north kiln
#

keep everything else the same except adding that

rocky geyser
north kiln
#

yeah

#

don't name it commands

rocky geyser
#

Else?

cloud dawn
#

You overwrite the imported commands from the discord.py module.

rocky geyser
#

Ok it worked

#

Thanks..

high narwhal
#

why doesnt the purge command work?..

#

it worked before, i added the verify thing now it doesnt work

proud rain
#

from .akinator_buttons import AkinatorButtons
ImportError: attempted relative import with no known parent package

How can i fix this?

slate swan
#
import asyncio
import os
import random
import discord
from discord.ext import tasks
from dotenv import load_dotenv

load_dotenv()  # load all the variables from the env file
bot = discord.Bot()

characters = [
    [
        "1",
        "https://cdn.discordapp.com/avatars/1095746248599949444/0cf827a34a40515b93fbd5715225adc4.png"
    ],
    [
        "2",
        "https://cdn.discordapp.com/avatars/433270158912389130/0f5a17577fa60bb205ddb50411fe9ed9.png"
    ],
]


@bot.slash_command(name="ping", description="check latency")
async def ping(ctx):
    await ctx.respond(f"Pong! {bot.latency}s")


@tasks.loop(seconds=20)
async def loop():
    n = random.randrange(0, 2)
    chnl = bot.get_channel(514087784026210305)
    char = characters[n]

    embed = discord.Embed(
        title="relic",
        description="A wild relic appeared!",
        color=discord.Color.blue(),
    )
    embed.set_image(url=char[1])

    def check(m):
        # check message content ignoring case and extra spaces
        return m.content.lower().strip() == char[0].lower() and m.channel == chnl

    try:
        await chnl.send(embed=embed)
        react = await bot.wait_for('message', check=check, timeout=400)
        await chnl.send(f"@{react.author.id}, you caught **{char[0]}**!")
    except asyncio.TimeoutError:
        await chnl.send(f"No one caught {char[0]}")


@bot.event
async def on_ready():
    if not loop.is_running():
        loop.start()  # If the task is not already running, start it.
        print(f"{bot.user} is online!")


bot.run(os.getenv('TOKEN'))

this code is able to send the characters, but i cant collect them for some reason, anyone knows why?

#

also the 20 seconds is temporary, when the bot is finished il set it to like 10 minutes

stark ingot
#

You would need the message content intent

hushed galleon
#

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

slate swan
#

in the bot settings

#

but do i need to add it to the code?

hushed galleon
#

yes, as per the above example (technically meant for discord.py but should be compatible with pycord)

slate swan
#

oh yea im using pycord

#

forgot to mention

#

it works now woo

stark ingot
#

๐ŸŽ‰

untold bear
#

My bot suddenly lost its embed colour, is this normal?

split vessel
untold bear
split vessel
#

happening to me too

candid flume
#
@discord.ui.button(label="Approve", style=discord.ButtonStyle.green, custom_id="approveBtn")
        async def approveBtn(self, interaction: discord.Interaction, button: discord.ui.Button):
            ## get the field from the embed ## ex01x
            code = interaction.message.embeds[0].fields[0].value

            ## update the database ## ex01x
            vouchStorage.update_one({"_id": code}, {"$set": {"status": "approved"}})

            ## send a message to the user ## ex01x
            try:
                user = bot.get_user(vouchStorage.find_one({"_id": code})["target"])
            except Exception as e:
                print(e)

            embed = discord.Embed(description=f"Your vouch with the ID `{code}` has been approved.", color=0x2ecc71)
            embed.set_author(name='Vouch Notification System')
            embed.set_footer(text="Made by Doare | Kudos!")

            await user.create_dm()

            try:
                await user.send(embed=embed)
            except:
                pass

            ## delete the message ## ex01x
            await interaction.message.delete()

I'm getting a 'NoneType' object is not subscriptable error due to me trying to use the bot.get_user

I've tried providing the class with self.bot but that did not work, is there a fix or an alternative way for this to work?

untold bear
split vessel
#

you can even notice that things are not sorted as how they were before not only the colors fading away

untold bear
#

Rip

nocturne hedge
#

Is there anyone here taking paid work at all? Looking for a discord Python bot developer:)

craggy notch
vale wing
#

Let's make a petition to discord to stop being goofy ahh

empty ferry
#

!intents

split vessel
empty ferry
#

Thanks

golden portal
#

no, you only use commands.Bot or discord.Client, not both, you should set message_content intents, messages intents is different, its a default intents where you receive the message object itself.

split vessel
#

๐Ÿค“

golden portal
#

" ๐Ÿค“ " ๐Ÿค“

latent veldt
#

slash commands examples link

#

can someone send

latent veldt
#

thank ku

shrewd apex
empty ferry
#

What should i do?

thin raft
#

avatar_url was in 1.7.3

#

now it is member.avatar.url

vestal acorn
#

just replace avatar_url by avatar

#

ok avatar.url

empty ferry
#

Thanks

#

It says Undefined

#

undefined member

thin raft
#

user....

empty ferry
#

O yea

slate swan
#
@bot.slash_command(name="collection", description="check your Boardex collection!")
async def collection(ctx):
    embed = discord.Embed(
        title="Boardex collection",
        description=f"{ctx.author.name}'s relics **(a lower number is more rare)**",
        color=discord.Color.blue(),
    )
    for cx in characters:
        ch = unidecode(cx[0].replace(" ", "_").replace(".", "").lower())
        c.execute(f"SELECT {ch} FROM users WHERE id = {ctx.author.id}")
        v = c.fetchone()[0]
        if v is None:
            embed.add_field(name=f"{cx[0]} (Rarity: {cx[2]})", value=f"You have 0 {cx[0]}(s)")
        else:
            embed.add_field(name=f"{cx[0]} (Rarity: {cx[2]})", value=f"You have {v} {cx[0]}(s)")
    
    await ctx.respond(embed=embed)

this code works but it breaks discords message limit, how could i divide it into pages of 15 characters?

empty ferry
#

buy nitro to bot

slate swan
#

๐Ÿ’€

#

i meant like, dividing the messages

#

because idk how to make the for loop stop at 15 characters, send it and start again

empty ferry
#

Oh, idk. I am just a newbie in python

high narwhal
#
async def on_voice_state_update(member, before, after):
    if after.channel and after.channel.name == "Join to Create":  # Check if member joined "Join to Create" channel
        guild = member.guild
        channel_name = f"{member.display_name}'s Channel"
        
        # Check if a channel with the same name already exists
        existing_channel = discord.utils.get(guild.channels, name=channel_name)
        
        if existing_channel:
            await member.send(f"A channel with your name already exists.")
            return

        overwrites = {
            guild.default_role: discord.PermissionOverwrite(connect=False),
            guild.me: discord.PermissionOverwrite(connect=True),
            member: discord.PermissionOverwrite(connect=True)
        }

        try:
            # Create voice channel
            new_voice_channel = await guild.create_voice_channel(name=channel_name, overwrites=overwrites, category=after.channel.category)
            await member.move_to(new_voice_channel)
            
            # Create text channel
            new_text_channel = await guild.create_text_channel(name=channel_name, overwrites=overwrites, category=after.channel.category)
            
            await member.send(f"Your channels '{channel_name}' have been created!")
        except discord.Forbidden:
            await member.send("I don't have permission to create channels.")

    if before.channel and before.channel.name.startswith(member.display_name) and len(before.channel.members) == 0:
        # Delete voice channel
        await before.channel.delete()

        # Find and delete corresponding text channel
        text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
        if text_channel:
            await text_channel.delete()```
how do i also delete the text channel when the custom voice channel has been deleted?
fickle aurora
fickle aurora
#

also I don't know what library you are using, but it looks somewhat similar to discord.py, so that shouldn't be much of a problem

quick gust
#

you can do something like

divided_characters = [characters[i : i + 15] for i in range(0, len(characters), 15)]

to make a new list with sublists and each sub list containing 15 characters

#

@slate swan

high narwhal
fickle aurora
fickle aurora
high narwhal
#

no errors no nothing

#

just not working.. idk why..

fickle aurora
#

hmm

#

what exactly do you expect it to do and when

high narwhal
#

so

#

when the voice channel gets deleted, i also want the text channel to get deleted

#

the voice channel gets deleted, but the text channel isnt (this is the problem)

fickle aurora
#

just its easier for me to view it that way

high narwhal
#

ye this is it

fickle aurora
#

so this part gets triggered ```py
if before.channel and before.channel.name.startswith(member.display_name) and len(before.channel.members) == 0:
# Delete voice channel
await before.channel.delete()

    # Find and delete corresponding text channel
    text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
    if text_channel:
        await text_channel.delete()```
#

and the voice channel gets deleted

#

but the text one doesn't right?

quick gust
# fickle aurora yeah that would seem like the solution for strings, but it seems that they want ...

well they said they wanted to show 15 characters per page (I personally don't think that would still be within the message limit) but they can divide the characters list into sublists of 15 characters each, and then loop through the sublists, and then the items of the sublists, while making a new embed for each sublist and then supplying the list of all the embeds to a paginator class (that's what I do atleast)

fickle aurora
quick gust
#

mhm

high narwhal
#

sadly

#

xd

fickle aurora
high narwhal
#

what is it??

fickle aurora
#

in here to search: text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)

#

but that is done after deleting the before.channel

high narwhal
#

ohhh

fickle aurora
#

so it doesn't have a name anymore

#

since it's been deleted

high narwhal
#

hmm

fickle aurora
#

you could just switch places

high narwhal
#

wonder how to fix it

#

wdym?

fickle aurora
#
    if before.channel and before.channel.name.startswith(member.display_name) and len(before.channel.members) == 0:
        text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
        # Delete voice channel
        await before.channel.delete()

        # Delete corresponding text channel
        if text_channel:
            await text_channel.delete()
#

like this ๐Ÿ˜†

high narwhal
#

ohh

#

i get so much errors

naive briar
#

Much!?

fickle aurora
#

yeah what does that mean

high narwhal
#

so many*

naive briar
#

That's pretty self-explanatory

high narwhal
#

and much more

quick gust
#

may I ask if you have previous experience with python, or coding in general?

fickle aurora
#

you pasted my code weirdly I think

high narwhal
#

nah, i can fix it
just saying what he said needed a fix, or just discord intended it bad xd

#

maybe he said it good just it pasted bad in vscode

quick gust
#

pretty sure u forgot to indent it

fickle aurora
#

yeah

high narwhal
#

umm

#

quitten, its still not deleting it

fickle aurora
#

@primal wave check the hosting thread of this channel

#

you can find useful info in the pins there

high narwhal
#

Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\userDownloads\veta-discord\main.py", line 275, in on_voice_state_update
await text_channel.delete()
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 822, in delete
await self._state.http.delete_channel(self.id, reason=reason)
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 741, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel

fickle aurora
#

huh

#

maybe the names of the voice and text channels differ

fickle aurora
#

or the channel already got deleted

high narwhal
#

ohhh yess

#

name different, ur right @fickle aurora

fickle aurora
#

Channel channel XD

high narwhal
#

bcs sadly discord doesnt allow text channels to have space and '

fickle aurora
#

and -'s

high narwhal
#

yeah :(

fickle aurora
#

well I suppose that can be solved easily

high narwhal
#

how??

fickle aurora
#

the .name should be str but lemme check the docs

#

yeah its str

#

so in the search instead of before.channel.name do some filtering with before.channel.name.lower().replace(' ', '-')

#

and the voice channel name should turn into the text channel name

high narwhal
#

it should be here

#

right?

#
        text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
        # Delete voice channel
        await before.channel.delete()

        # Delete corresponding text channel
        if text_channel:
            await text_channel.delete() ```
non modified code, as u can see i have more before.channel.name, but what you are saying its supposed to be on the first line right?
#

so the code should look like this:

        text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
        # Delete voice channel
        await before.channel.delete()

        # Delete corresponding text channel
        if text_channel:
            await text_channel.delete()```
fickle aurora
#

no in the search

high narwhal
#

wdym?

fickle aurora
#

nono, when you search the channel

high narwhal
#

ohh

fickle aurora
#

... = discord.utils.get(..., name=before.channel.name.lower().replace(' ', '-'))

high narwhal
#

yee, thanks bro

#

lemme test it

#

no error, but no delete..

fickle aurora
#

try printing it before deleting

high narwhal
fickle aurora
#

print(text_channel)

high narwhal
#

ok ok

fickle aurora
#

oh ' gets removed too

high narwhal
#

ye

fickle aurora
#

so need to add .replace("'", "")

#

like that ... = discord.utils.get(..., name=before.channel.name.lower().replace(' ', '-').replace("'", ""))

high narwhal
#

YOO

#

IT WORKED
tysm broo

fickle aurora
#

because people are weird and they can put weird stuff in their nicknames

high narwhal
#

huh? wdym

#

oh, yeah..

fickle aurora
#

and the channel name is based on their nickname

high narwhal
#

i will also add things for those

fickle aurora
#

so that might break it at some point

high narwhal
#

by things i mean replace

fickle aurora
#

alright then, good luck

high narwhal
#

thanks :D

quick gust
#

could also use regex

empty ferry
#

hey guys, i made warn command and i warned myself, the warn is not saving in database

fickle aurora
empty ferry
#

Okay

fickle aurora
#

how do you save the data to the database? which database do you use?

empty ferry
#

sqlite 3

fickle aurora
empty ferry
#

ye

#
@commands.has_permissions(kick_members=True)
async def warn(ctx, user: discord.Member, *, reason: str):
    c.execute('SELECT count FROM warnings WHERE user_id=?', (user.id,))
    result = c.fetchone()

    if result is None:
        c.execute('INSERT INTO warnings VALUES (?, 1)', (user.id,))
    else:
        c.execute('UPDATE warnings SET count=? WHERE user_id=?', (result[0] + 1, user.id))
    
    await ctx.send(f'{user.name} has been warned.')
    conn.commit()
@bot.command()
async def warns(ctx, user: discord.Member = None):
    if not user:
        user = ctx.author
    # ะฟะพะปัƒั‡ะฐะตะผ ะบะพะปะธั‡ะตัั‚ะฒะพ ะฟั€ะตะดัƒะฟั€ะตะถะดะตะฝะธะน ะดะปั ะฟะพะปัŒะทะพะฒะฐั‚ะตะปั
    c.execute("SELECT warns FROM warns WHERE user_id=? AND guild_id=?", (user.id, ctx.guild.id))
    result = c.fetchone()
    if result is None:
        warns = 0
    else:
        warns = result[0]
    # ะพั‚ะฟั€ะฐะฒะปัะตะผ ัะพะพะฑั‰ะตะฝะธะต ั ะบะพะปะธั‡ะตัั‚ะฒะพะผ ะฟั€ะตะดัƒะฟั€ะตะถะดะตะฝะธะน
    embed = discord.Embed(title=f'Warns for {user.name}', color=0x00ff00)
    embed.add_field(name='Warns', value=warns, inline=False)
    await ctx.send(embed=embed)```
fickle aurora
#

ok, I would recommend using an async library, but for starters that's okay I guess

empty ferry
#

ok nice thx

fickle aurora
#

what are c and conn?

empty ferry
#

idk, i found this code on internet

fickle aurora
#

actually conn is a connection and c is a cursor I suppose

empty ferry
#

Ohh

fickle aurora
empty ferry
fickle aurora
#

I bet russian tutorials are good asf ๐Ÿ’€

empty ferry
#

maybe lol

fickle aurora
#

I haven't seen a good one in english

#

nor in russian lol

#

anyway, you should note that if you are using code, you should understand what and how it is doing

#

it is not a secret that developers copy paste a lot, but not understanding what your code does is quite... not nice

#

now.. back to solving the problem

#

I suspect that the connection is set up improperly

#

@empty ferry can you send the code where it says conn = ...?

empty ferry
#
# creating a connction to database
conn = sqlite3.connect('warnings.db')
c = conn.cursor()```
fickle aurora
empty ferry
#

ye

twilit grotto
#

show your database structure

fickle aurora
#

yeah that would make sense

twilit grotto
#

that doesn't show me the database structure

fickle aurora
twilit grotto
#

show me your tables in the database

fickle aurora
#

the tables, their columns

empty ferry
#

I havent created them.. so should i create them?

twilit grotto
#

....

#

you need to make the structure of the database lol

empty ferry
#

how

#

some websites like phpmyadmin?

fickle aurora
fickle aurora
empty ferry
#

thanks, now going to make them thumbsup

twilit grotto
fickle aurora
fickle aurora
empty ferry
#

and sqlite dll win x64 folder

twilit grotto
#

dawg huh.

#

ur overcomplicating it, look at the link i sent you

fickle aurora
#

yeah

empty ferry
#

okey

#

ok now what im gonna do rn

twilit grotto
#

change the table name, and change the columns to what you need.

fickle aurora
#

I'm surprised the tutorial you read doesn't give that to you

empty ferry
#

ok

#

table is ready

#

whats next now?

twilit grotto
#

show me what it looks like

empty ferry
#

or this

twilit grotto
#

no. you need to change your query to be correct, change it to have the table name 'warnings' and then change the column names

empty ferry
#

oh

twilit grotto
#
CREATE TABLE IF NOT EXISTS warnings (
    user_id INTEGER,
    count INTEGER,
    PRIMARY KEY (user_id)
);
```something like this would probably work for you just fine
twilit grotto
#

oh yeah reason too i forgot that

fickle aurora
#

there are no arrays in sqlite tho

empty ferry
fickle aurora
#

so you'd have to unprimary key the user_id

twilit grotto
#

ah i didn't know that, thats aids

fickle aurora
twilit grotto
#

and you also might have to change it from an integer to something else because im pretty sure userid's are too long to store them as an integer

empty ferry
junior night
#

Cool story bro!

empty ferry
fickle aurora
#

snipy hey!!!

#

long time no see

empty ferry
#
import sqlite3
 
# Connecting to sqlite
# connection object
connection_obj = sqlite3.connect('warnings.db')
 
# cursor object
cursor_obj = connection_obj.cursor()
 
# Drop the GEEK table if already exists.
cursor_obj.execute("DROP TABLE IF EXISTS GEEK")
 
# Creating table
table = """ CREATE TABLE GEEK warnings (
            Email *hidden* (255) NOT NULL,
            First_Name ascii(25) NOT NULL,
            Last_Name(25),
            Score INT
        ); """
 
cursor_obj.execute(table)
 
print("Table is Ready")
 
# Close the connection
connection_obj.close()``` now?
twilit grotto
#

HUH

empty ferry
#

?

fickle aurora
twilit grotto
fickle aurora
#

oh hell nah

empty ferry
#

????

fickle aurora
#

i thought that was from geeks for geeks

#

they are weird sometimes

#

like maybe sqlite allowed that

glad cradle
#
CREATE TABLE IF NOT EXISTS warnings(
    id     INT NOT NULL AUTO_INCREMENT,
    user_id BIGINT NOT NULL,
    reason TINYTEXT
);

this should work for your Bot

fickle aurora
#

count?

#

I don't think he needs ids here

glad cradle
fickle aurora
#

nor count

glad cradle
#

trye

#

count is useless the id must be there

glad cradle
glad cradle
fickle aurora
glad cradle
#

in the table there could be multiple rows with the same user_id and the way to ensure uniqueness is to have a randomly generated id for every warning entry

glad cradle
#

which is not cool imo (having an array i mean)

fickle aurora
#

having an array is cool but not possible in sqlite

#

and I don't think you need the radnom ID, it can just be incrementing

empty ferry
twilit grotto
glad cradle
fickle aurora
#

it's hard when ppl start with discord bots in their python journey

#

especially when they try things a little harder than what they can do

fickle aurora
glad cradle
empty ferry
#

oh

glad cradle
hushed galleon
lone aurora
#

.

#

where can i ask about tkinter?

hushed galleon
lone aurora
#

ty

shrewd venture
#

Hey i would like to ask for advice what to add to my discord bor, is this the place to do so? i am not quite sure ๐Ÿ˜„

sinful surge
#

py-cord is the best discord bot library of all time

pale zenith
sinful surge
#

what do you mean leonardo

#

are you a MATTYLAB dev?

pale zenith
#

I just disagree with your opinion

sinful surge
#

ok

pale zenith
sinful surge
#

ok

river plank
naive briar
torn solar
#
def getStockInfo(ticker_symbol, api):
    url = f'https://api.twelvedata.com/quote?symbol={ticker_symbol}&apikey={api}'
    response = requests.get(url).json()
    name = response['name']
    high = response['high']
    low = response['low']
    vol = response['volume']```
how can i grab each individual variable
#

like i want to get name, high, low, and vol

#

whoops wrong area sorry

river plank
torn solar
latent jay
#

yeah

formal basin
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

formal basin
shrewd apex
#

u probably have some blocking code

formal basin
shrewd apex
#

requests is blocking

formal basin
#

is it?

shrewd apex
#

u need to use aiohttp

formal basin
#

ok i will

#

thnak you

formal basin
#

the dog one

shrewd apex
#

everywhere ur using requests

#

needs to be changed to aiohttp

formal basin
#

ok

zenith yarrow
#
@bot.tree.command()
async def reactionroleadd(interaction: discord.Interaction, role: discord.Role, emoji: str , message_link: str):
  embed = discord.Embed(title="Reaction Role created", description="Those who will react will get the role")
  await interaction.response.send_message(embed=embed)
  message = await interaction.channel.fetch_message(message_link)
  if message.reaction.emoji == emoji:
    await user.add_roles(role)

Upon using this command it gives a very long error

naive briar
#

Send the error then

dawn delta
#

i need help,

    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.```
naive briar
#

Read the error

dawn delta
#

yeah i don't understand what's privileged intents

#

oh i found the setting my bad

#

wooho

dawn delta
quick gust
#

re run the bot

dawn delta
quick gust
#

by closing the terminal that's running the bot...

dawn delta
#

oh there's no a command for it?

#

awh

quick gust
#

well if ure using cogs u can reload it

dawn delta
#

im using vsc

quick gust
#

!d discord.ext.commands.Bot.reload_extension

unkempt canyonBOT
#

reload_extension(name, *, package=None)```
Atomically reloads an extension.

This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://docs.disnake.dev/en/latest/ext/commands/api/bots.html#disnake.ext.commands.Bot.unload_extension) followed by a [`load_extension()`](https://docs.disnake.dev/en/latest/ext/commands/api/bots.html#disnake.ext.commands.Bot.load_extension) except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
quick gust
dawn delta
quick gust
#

!d discord.ext.commands.Cog take a look

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta) are equally valid here.
dawn delta
#

i tried close and open the bot again then use py. main.py(its my file name), now it shows this py Traceback (most recent call last): File "D:\atest-bot\main.py", line 20, in <module> @client.command() ^^^^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1520, in decorator result = command(name=name, cls=cls, *args, **kwargs)(func) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1793, in decorator return cls(func, name=name, **attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 406, in __init__ self.callback = func ^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 513, in callback self.params: Dict[str, Parameter] = get_signature_parameters(function, globalns) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 130, in get_signature_parameters raise TypeError(f'Command signature requires at least {required_params - 1} parameter(s)') TypeError: Command signature requires at least 0 parameter(s)

#

hmm

quick gust
#

you'll also have to share the code

dawn delta
#
import discord
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

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

@client.event
async def on_ready():
    print("Is logged in")

@client.command()
async def hello(ctx):
    await ctx.send("Hello!")
    
@client.command()
async def ping():
    await client.say('Pong')

client.run```
#

it works earlier, but not anymore

quick gust
#

try giving the command a name in the decorator

dawn delta
#

which

golden portal
#

well that's a misleading error

golden portal
#

client.say doesnt exist anymore btw, use ctx.send

dawn delta
#

oh

#

okay thanks, i was getting the reference from google

golden portal
dawn delta
dawn delta
# golden portal every command must have context as param, so do `async def ping(ctx):` instead
Traceback (most recent call last):
  File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\atest-bot\main.py", line 22, in ping
    await ctx.send("Pong")
          ^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'send'

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

Traceback (most recent call last):
  File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'send'```
#

???

golden portal
#

code

dawn delta
#

it's the same

#

๐Ÿ˜ญ

golden portal
#

error doesnt match code, did you save the file

dawn delta
#

OH I NEED TO SAVE? MY BAD ๐Ÿ˜ญ

dawn delta
#

YAY IT WORKS

dawn delta
golden portal
#

err, yes? if your IDE have an auto-save feature you dont have to

dawn delta
#

but it didn't

#

uh idk, maybe it only works when it changed

golden portal
#

what IDE is this

dawn delta
#

what's IDE? the code editor? it's VSC

golden portal
#

i see

#

vsc i think have a little bit of delay so you probably ran it before it auto save

#

pycharm autosave instantly

dawn delta
#

i've seen someone used pycharm and tbh it looks weird, as hell

golden portal
#

sounds like human issue

dawn delta
#

those ppl send stuff like 2018 ish wth

#

hmm yeah i know it's reference but what does the (message) mean

golden portal
#

I'm not sure what you're asking exactly

dawn delta
golden portal
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
dawn delta
#

oh wait

#

yeah

#

is it okay?

#

it won't trigger tho

golden portal
#

it's just await message.channel.send('them')

dawn delta
golden portal
#

nope

dawn delta
golden portal
#

yes

dawn delta
#

thank you!!!

golden portal
#

welcome

dawn delta
#

@golden portal do you know what should i fix?

#

there's no error code in the code viewer thing

finite salmon
#

Either way you're probably better off making a command tho

dawn delta
#

omg help

#

my bot won't respond anymore

#

๐Ÿ˜ญ

pale zenith
#

Do you have another function with that name?

shrewd fjord
north timber
#

sorry I know it's not related, just got curious lol

long pecan
pale zenith
fathom wind
upbeat otter
fathom wind
slate swan
#

you have to sync when you change names

dawn delta
dawn delta
ebon ocean
#

Has anybody else made Deal or No Deal game with their discord bot before? Actually does anybody like making games on discord bots? That my thing.

ebon ocean
#

Um... okay.

valid perch
#

A lot of people have likely made games, and im sure some have done deal or no deal before as well

ebon ocean
#

I be very shocked if anybody done that. In fact, I'll be shocked if anybody even made a better version than the one I made. Well technically, I'm making a new improved version, but one thing trips me up.

I have never been able to figure out how they split their discord stuff into different files. Currently, every game and thing I have is on the same file.

storm leaf
#

Any one got a quick tip on how to sync my discord commands? Fiddling with discord again after a year or so, and I've somehow got duplicate commands. Tried limiting it to just guild, but no success. Any ideas?

dawn delta
#

the website are not valid anymore

slate plover
#

oooraaah

north kiln
storm leaf
north kiln
#

how are you syncing them?

storm leaf
#
@bot.event
async def on_ready():
    await bot.tree.sync(guild=discord.Object(id=YOUR_GUILD_ID))```
#

That's what I found

north kiln
#

I think you have synced to global before, they won't disappear after you synced to guild

storm leaf
#

That is most likely the issue now that you say it, makes sense. Now can I desync them from global?

#

How*

north kiln
#

sync an empty tree to global, (so don't pass guild=) if all your commands are guild specific it should already be empty

slate plover
#

@supple locust where did you find user_from?

#

I can't find it on the API

zenith yarrow
#

How to make a argument optional in a slash command

storm leaf
#

Like so?

#

I assume I need to remove the commands that are syncing to the guild?

slate plover
#

@supple locust is this how it is supposed to look?

supple locust
#

are you not using client = commands.Bot() at like the top of your code? I thought you were

#

which means you should use client.get_user()

slate plover
#

im already using client for something else

supple locust
#

Oh then yes

#

bot

slate plover
#

heh, here we go again

supple locust
#

This is why I said you probably want to make sure you check if anything is None along the way

north kiln
#

typehint the argument with typing.Optional

supple locust
#

the full thing would be typing.Optional[ScheduledEvent]?

slate plover
#

i think

supple locust
#

try what HyperCube is saying

north kiln
#

I am not replying to him

#

the original message was deleted

slate plover
#

ill try this

north kiln
#

@slate plover you should send your whole code to give better context

#

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

north kiln
#

but remember to hide your token

supple locust
north kiln
#

There shouldn't be both clients and bot in your code

#

how did you run the bot

#

client.run or bot.run

slate plover
#

fuck, now you made sense

#

@north kiln Can't I just run both client.run and bot.run?

north kiln
#

no

#

for the event problem, if you have a creator id dpy will attempt to set event.creator by creating a user from the id

#

so what you are facing is quite weird

#

maybe you should ask in dpy server

slate plover
#

I just dropped on them the paste link

vestal moss
#

hlo so i was gone for 3 years

#

what changes will i have to done to make my bot run again

supple locust
#

eventUser = await bot.get_user(event.creator_id).create_dm(eventUser).send("Your event got cancelled.")
also this line is a problem, because you're trying to use eventUser in the create_dm() method before you've defined it, and that's also not how create_dm() is meant to be used, I'm positive it doesn't take any arguments. You're best to get rid of eventUser = and just use create_dm() not create_dm(eventUser)

vestal moss
#
import discord
from keep_alive import keep_alive
from discord.ext import commands
intents = discord.Intents.all()
activity=discord.Activity(name='Knife HQ pre alpha 0.0.1 \n prefix = pls', type=discord.ActivityType.watching)
bot=commands.Bot(command_prefix=["pls ","Pls ","PLS ","PLs ","PlS ","pLs  ","pLS "],case_insensitive=True,activity=activity,intents=intents)
bot.load_extension('cogs.auto_task')
bot.load_extension('cogs.Battle')
keep_alive()```
#

discord.ext works still?

#

and cogs also

north kiln
#

both works

#

But bot.load_extension is now coro

slate plover
#

@supple locust same error
AttributeError: 'NoneType' object has no attribute 'create_dm'

supple locust
#

use client.get_user instead might work

#

since you're using bot and client it might be getting confused

#

you really should stick with just not

#

bot everywhere

slate plover
#

I hate python

#

ORRAAAAH