#discord-bots

1 messages · Page 380 of 1

wild gate
#

im just gonna work it on myself

fast osprey
#

There's not a single question mark in that post

willow sluice
#

@wild gate what is your question lol

willow sluice
#

@wild gate You did not ask a single question but i guess you need something like that

from aiohttp import web, web_request, ClientSession
from discord.ext import commands
import json
import subprocess


class WebServer(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        self.api_url = 'http://localhost:5000'

    @commands.command()
    async def execute(self, ctx: commands.Context, *, command):
        async with ClientSession() as session:
            url = self.api_url + '/execute'
            data = {'command': command}

            async with session.post(url, data=json.dump(data)) as response:
                if response.status_code == 200:
                    await ctx.channel.send(f'Command executed: {command}')
                else:
                    await ctx.channel.send(f'Failed to execute command: {command}')

    async def execute_command(self, request: web_request.Request):
        data = await request.json()
        command = data.get(command)
        try:
            result = subprocess.checkoutput(command,
                stderr=subprocess.STDOUT,
                shell=True,
                text=True)
            return web.Response(
                status=200,
                text=json.dumps({"result": result}),
                content_type='application/json')
        except subprocess.CalledProcessError as e:
            return web.Response(
                status=400,
                text=json.dumps({"error": str(e.output)}),
                content_type='application/json')

    async def cog_load(self):
        app = web.Application()

        runner = web.AppRunner(app)
        await runner.setup()

        site = web.TCPSite(runner, host='0.0.0.0', port=5000)
        await site.start()

        app.router._frozen = False
        app.router.add_post('/execute', self.execute_command)
        app.router.freeze()


async def setup(bot):
    await bot.add_cog(WebServer(bot))
wild gate
# willow sluice <@194921713555865600> what is your question lol

well I get a bit better understanding now what I need to do, it's like if I host a server on like a digital ocean VM what would it look like not in terms of code but more like what do I need to do if I want to have the application waiting for commands from the discord bot

#

like the code I can always figure out

#

it's more the idea of what am I doing I need a better understanding of

fast osprey
#

What you asked was fairly general. What are users doing, what are the "commands" you're looking to run? What is the overall purpose?

wild gate
# fast osprey What you asked was fairly general. What are users *doing*, what are the "command...

It's to connect to a game, I mean it's just basic like / commands in the discord server, and for the commands they're just functions that'll do stuff in game I already have built I just need like info on what I need to do in terms of hosting like do I need a server or can I just run it all on a VM that is hosted by digital ocean and like just have my discord bot connect to the VM, like i have no idea what I need to do in terms of hosting basically

#

idk I'm wathcing a few yt videos rn on discord bots my questions will prolly be clearer in a bit I'm just gonna ask tmrw

fast osprey
#

Anywhere you could run a python program, you could run a discord bot. Just needs network access to discord and a few libraries

#

Any other requirements are entirely what you're doing inside of that bot, i.e. running other stuff, connecting to other systems, etc etc

mild token
#

why other member can also search for this command if i have locked this command to myself?

uneven fiber
#

RuntimeError: Numpy is not available

mild token
uneven fiber
#

i did

mild token
#

how many python version are available?

uneven fiber
#

how i check

mild token
#

py --version

uneven fiber
#

3.11.9

hushed galleon
mild token
mild token
uneven fiber
#

then what

mild token
#

see its installed or not

uneven fiber
#

it is

mild token
#

have u tried the command?

uneven fiber
#

yes

mild token
#

btw by any chance r u working in virtual env?

uneven fiber
#

no

mild token
#

i recommend u to do that then u wont have these kind of issue

#

i personally use poetry to manage the virual env and dependencies

hushed galleon
uneven fiber
#

its a error w my other bot

mild token
uneven fiber
#

dms

mild token
# uneven fiber dms

please refrain from using that 😅 asking here will benefit even more user with same issue

#

saves effort and time

uneven fiber
#

says this now

mild token
#

you can see above

#

one sec woops

#

commands is from ext

#

try discord.Client

uneven fiber
mild token
# uneven fiber

hmm do like this

class MyBot(commands.Bot):
       def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


bot  = MyBot(intents=intents)
uneven fiber
#

where

mild token
#

define it

uneven fiber
#

how

#

i js started python

mild token
uneven fiber
#

well

#

how do i define it

mild token
#

even if i tell u , u wont be able to make changes if u dont understand what the error is trying to say

uneven fiber
#

can u still tell me

mild token
#

this will be last chance i am spoonfeeding u after this time please complete your basics first

intents = discord.Intents.all()
#

this will enable all intents

uneven fiber
mild token
#

i wont tell answer of this u need to figure it out , its clearing stating whats the issue , please refer to the docs

uneven fiber
#

bro, im just trying to get help dude

mild token
#

!d discord.ext.commands.Bot.command_prefix

unkempt canyonBOT
#

The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.

An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it’s likely to cause performance issues and unintended command invocations.

mild token
uneven fiber
#

im not a dev, im js tryna run this bot for my friend

mild token
uneven fiber
#

i dont wanna add cmds

mild token
#

then googling can help

uneven fiber
#

chatgpt

mild token
#

!rule 10

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

uneven fiber
#

oh ok

#

bot = commands.Bot(command_prefix='!') should it look like this?

mild token
#

yep

uneven fiber
#

but idk how to put it into the MyBot

mild token
#

btw u need to use mybot

uneven fiber
mild token
uneven fiber
#

ok

#

can u send it

#

or help me fix TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'

uneven fiber
#

im just gonna ask someone else

#

can u atleast help with my numpy

mild token
uneven fiber
#

RuntimeError: Numpy is not available

mild token
uneven fiber
#

no cus i did pip install numpy

mild token
uneven fiber
#

Python 3.11.9

mild token
#

see it install or not

uneven fiber
#

Requirement already satisfied:

mild token
uneven fiber
#

ye cus i tried to use 3.2 to see if it fixed but it didnt so i went back to 3.1 and uninstalled 3.12

mild token
#

see it solves or not

uneven fiber
#

no such option: -m

mild token
uneven fiber
#

Requirement already satisfied

mild token
#

pip show numpy also showing?

uneven fiber
#

yes

mild token
#

i dont have idea what to do if your current py has numpy installed and its not showing it and u r claiming only 1 py version u have

uneven fiber
mild token
#

is there any event which tells who deleted the message if its the author himself?

uneven fiber
#

no

brazen crane
#

in discordpy, whats the difference between on_error and on_command_error

mild token
#

!d discord.discord.ext.commands.on_command_error

unkempt canyonBOT
#

discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error)).
mild token
#

!d discord.app_commands.CommandTree.on_error

unkempt canyonBOT
#

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

A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError).

The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.

To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command) should be used.
mild token
#

@brazen crane

brazen crane
#

thanks

mild token
#

yw

brazen crane
#

is on_application_command_error a thing?

mild token
brazen crane
#

idrk

mild token
#

Have u checked the docs?

#

Don't think anything like that exists

brazen crane
#

hhhmmm yea i dont think so

finite salmon
#

A pretty useful error handler for slash commands idk what's it called in dpy if it exists

vocal laurel
finite salmon
#

O

mild token
#

on_raw_member_remove and on_member_remove whats the difference like raw one can be called ? like if bot isnt online it wont post then in what scenario raw on will be useful?

torn solar
#
# News Command Group
@commands.group(name="news", invoke_without_command=True)
async def news(ctx):
    if ctx.invoked_subcommand is None:
        await ctx.send('Invalid news command.')

# Subcommands for news command
@news.command(name='setreviewchannel', description="Set review channel for news articles.")
async def news_setreviewchannel(ctx, channel: discord.TextChannel):
    try:
        with open('main.json', 'r') as f:
            data = json.load(f)
    except FileNotFoundError:
        data = {}

    data['review_channel_id'] = channel.id

    with open('main.json', 'w') as f:
        json.dump(data, f, indent=4)

    await ctx.send(f'Review channel set to {channel.mention}')``` i did the command group in attempt to have spaces in the commands not dashes but theres still dashes
#

@turbid condor you available for this one

#

like i wanted it to show as /news setreviewchannel

#

but its /news-setreviewchannel

turbid condor
torn solar
#

how can i fix

turbid condor
#

What fix make it a app_command group or hybrid_group

torn solar
#

like this right? and the what should i do for the subcommands decorator

turbid condor
#

use news

#
from discord.app_commands import Group, command
from discord.ext.commands import GroupCog

# option 1 - this can be used inside a cog
my_group = Group(name='group', description='description')

@my_group.command()
async def subcommand(interaction: Interaction):
  ...

subgroup = Group(parent=my_group, name='subgroup', description='description')

@subgroup.command()
async def subsubcommand(interaction: Interaction):
  ...

tree.add_command(my_group)

# option 2 - this cannot be used inside a cog
class MyGroup(Group, name='group', description='description'):
  @command()
  async def subcommand(self, interaction: Interaction):
    ...

  subgroup = Group(name='subgroup', description='description')

  @subgroup.command()
  async def subsubcommand(self, interaction: Interaction):
    ...

tree.add_command(MyGroup())

# option 3 - this IS a cog
class MyGroup(GroupCog, group_name='group', group_description='description'):
  @command()
  async def subcommand(self, interaction: Interaction):
    ...

  subgroup = Group(name='subgroup', description='description')

  @subgroup.command()
  async def subsubcommand(self, interaction: Interaction):
    ...

await bot.add_cog(MyGroup())  # this is the only time guild(s) kwarg is valid in add_cog
```Note: Groups can only be nested once. <https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups>
#

These are 3 different methods

torn solar
# turbid condor These are 3 different methods
    
@news.command(name="news-setreviewchannel", description="Set review channel for news articles.")
async def new_setreviewchannel(interaction: discord.Interaction, channel: discord.TextChannel):
    try:
        with open('main.json', 'r') as f:
            data = json.load(f)
    except FileNotFoundError:
        data = {}
        
    data['review_channel_id'] = channel.id
    
    with open('main.json', 'w') as f:
        json.dump(data, f, indent=4)
        
    await interaction.response.send_message(f'Review channel set to {channel.mention}')``` did i do something wrong all of my commands dissapeared
fast osprey
#

How is Group defined, and how is this being added to your bot?

mild token
finite salmon
#

although for this specefic event the chances of the member not being in the cache in a normal state is really low

#

but if your bot is present in a lot of servers (probably 5k+ i think?), the chances of the member not being cached will be common i guess

boreal sigil
#
# BAN CMD
@commands.has_permissions(ban_members=True)
@commands.hybrid_command()
async def ban(ctx, user: discord.User, *, reason="***No reason provided.***"):
        """ Bans a user from the guild """
        ban = discord.Embed(title=f"![bonk](https://cdn.discordapp.com/emojis/1255222332830515304.webp?size=128 "bonk") | Banned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}", color = discord.Color.brand_red())
        await ctx.message.delete()
        await ctx.channel.send(embed=ban)
        bandm = discord.Embed(title=f"![bonk](https://cdn.discordapp.com/emojis/1255222332830515304.webp?size=128 "bonk") | You were Banned!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
        await user.send(embed=bandm)
        await ctx.guild.ban(user)

# UNBAN CMD
@commands.hybrid_command()
async def unban(ctx, user: discord.User, *, reason="***No reason provided.***"):
        """ Unbans a user from the guild """
        unban = discord.Embed(title=f"![catcri](https://cdn.discordapp.com/emojis/1248705148293742723.webp?size=128 "catcri") | Unbanned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}", color = discord.Color.brand_green())
        hellowhat = discord.Embed(title=f"![NOO](https://cdn.discordapp.com/emojis/1248704955653820436.webp?size=128 "NOO") | {user.name} isn't Banned!", color = discord.Color.teal())
        try:
            entry = await ctx.guild.fetch_ban(discord.Object(user.id))
        except discord.NotFound:
            await ctx.channel.send(embed=hellowhat)
        await ctx.guild.unban(discord.Object(user.id))
        await ctx.channel.send(embed=unban)
        await ctx.message.delete()
        return

My bot doesnt see this code - I look in the help menu and there isnt a ban/unban cmd at all

#

even do +ban or +unban and nothing

#

terminal says command not found

fast osprey
#

How are these being added to the bot?

#

Also you really should not be making a thin wrapper over sensitive things that already exist while stripping away the security

boreal sigil
#

like the rest of the cmds

#

just in the file

fast osprey
#

Show what is adding these commands to the bot

boreal sigil
#

what

#

normally you just define the bot command and do the async stuff

fast osprey
#

"Async stuff"?

#

Something needs to add commands to a bot

boreal sigil
#

i have a sync command

fast osprey
#

Just declaring a command in the ether doesn't make the bot magically know about it

boreal sigil
#

sync all the slash commands

boreal sigil
fast osprey
#

It's not

boreal sigil
#

i think

fast osprey
#

There is something that adds those commands to the bot

boreal sigil
#

which is?

fast osprey
#

I can't tell you how your code works that you haven't shown

boreal sigil
#

im confused

#

what am i missing?

fast osprey
#

Code that adds these commands to your bot

#

This code you sent declares a command. Nothing tells the bot that it exists, that you've shown

boreal sigil
#
# SYNC SLASH COMMANDS WITH <prefix>sync
from typing import Literal, Optional
@bot.command()
@commands.guild_only()
@commands.is_owner()
async def sync(ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
    if not guilds:
        if spec == "~":
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "*":
            ctx.bot.tree.copy_global_to(guild=ctx.guild)
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "^":
            ctx.bot.tree.clear_commands(guild=ctx.guild)
            await ctx.bot.tree.sync(guild=ctx.guild)
            synced = []
        else:
            synced = await ctx.bot.tree.sync()

        await ctx.send(
            f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
        )
        return

    ret = 0
    for guild in guilds:
        try:
            await ctx.bot.tree.sync(guild=guild)
        except discord.HTTPException:
            pass
        else:
            ret += 1

    await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")

i have this ig

#

thats my sync command

fast osprey
#

This tells discord about commands your bot knows about

#

This does not tell your bot about commands it doesn't know about

boreal sigil
#

then what do I do to make my bot recognise them

#

ill take a docs link at this point i dont even need code

fast osprey
#

Please send the full file these commands are in

boreal sigil
#

alright

#

enjoy the mayhem that code is

fast osprey
#

Compare these commands to the commands that are working

willow sluice
#

is there a way to get the raw message from an discord.Message? i mean json format like Message Object

i found on_socket_raw_receive and this is working but i still wonder is it possible to make it inside regular events eg on_message

boreal sigil
fast osprey
#

Look at the command decorator

#

There is a key difference between the one that works and the one that doesn't

boreal sigil
#

oh

#

wait what

#

it looks identical

boreal sigil
#

even the docs show what im using

fast osprey
#

Post the two of them here, side by side. Just the command decorator. For one that works and one that does not

boreal sigil
#

Working:

# UNHIDE CMD
@bot.hybrid_command()
@commands.has_permissions(manage_channels=True)
async def unhide(ctx, channel : Optional[discord.TextChannel] = None):
    """ Unhides the channel the command is used in, or a specified channel """

Not working:

# BAN CMD
@commands.hybrid_command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, user: discord.User, *, reason="***No reason provided.***"):
        """ Bans a user from the guild """
fast osprey
#

Read those

#

And tell me they are the same

boreal sigil
#

oh

#

im stupid af-
i switched them between files tryna split it all up and didnt change it back

slate swan
#

Sometimes I ask myself what's the purpose of a ban command

boreal sigil
#

to enjoy the power you have

fast osprey
#

There isn't one besides pretending to be more useful than you are while reducing security

boreal sigil
#

next is this fine and if it isnt how do i fix

fast osprey
#

And do you understand why those are different?

boreal sigil
#

yeah

boreal sigil
fast osprey
#

that's not an error

quick gust
#

that's just a warning

fast osprey
#

You're just making a variable you never use

quick gust
#

it means ure not using a variable ure declaring

willow sluice
fast osprey
#

You would need to describe why it is you want the raw object

willow sluice
#

I want to send the raw message object to a third party server when the message is sent or edited
I can explain more specifically if you need

boreal sigil
#

Hey so I made a cog names 'Configuration' and successfully added one command to it but when I try and add another it gives me a massive error - how do I add a command to an already made cog? Code below.

class Configuration(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
# SYNC SLASH COMMANDS WITH <prefix>sync
    @commands.hybrid_command()
    @commands.guild_only()
    @commands.is_owner()
    async def sync(ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
        if not guilds:
            if spec == "~":
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "*":
                ctx.bot.tree.copy_global_to(guild=ctx.guild)
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "^":
                ctx.bot.tree.clear_commands(guild=ctx.guild)
                await ctx.bot.tree.sync(guild=ctx.guild)
                synced = []
            else:
                synced = await ctx.bot.tree.sync()

            await ctx.send(
                f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
            )
            return

        ret = 0
        for guild in guilds:
            try:
                await ctx.bot.tree.sync(guild=guild)
            except discord.HTTPException:
                pass
            else:
                ret += 1

        await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")

# PING CMD
@commands.hybrid_command()
async def ping(ctx):
    """ Replies with the Bot's latency """
    await ctx.send(f"Pong! {int(bot.latency*1000)}ms")
willow sluice
#

Send the error

boreal sigil
#

Error:
Traceback (most recent call last): File "c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py", line 84, in <module> class Configuration(commands.Cog): File "c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py", line 86, in Configuration @commands.hybrid_command() ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\hybrid.py", line 909, in decorator return HybridCommand(func, name=name, with_app_command=with_app_command, **attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\hybrid.py", line 509, in __init__ super().__init__(func, **kwargs) File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 406, in __init__ self.callback = func ^^^^^^^^^^^^^ File "C:\Users\a\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\a\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 1 parameter(s)

boreal sigil
#

btw
removed cogs code from shown above

#

in the ping bit

willow sluice
#

you forgot to add self inside your sync command arguments

boreal sigil
#
class Configuration(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
# PING CMD
    @bot.hybrid_command()
    async def ping(ctx):
        """ Replies with the Bot's latency """
        await ctx.send(f"Pong! {int(bot.latency*1000)}ms")

this was my attempt but idrk

dense falcon
#

^^ in commands like this, you need self and ctx

boreal sigil
#

ahhh ok

#
class Configuration(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
# SYNC SLASH COMMANDS WITH <prefix>sync
    @commands.hybrid_command()
    @commands.guild_only()
    @commands.is_owner()
    async def sync(self, ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
        if not guilds:
            if spec == "~":
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "*":
                ctx.bot.tree.copy_global_to(guild=ctx.guild)
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "^":
                ctx.bot.tree.clear_commands(guild=ctx.guild)
                await ctx.bot.tree.sync(guild=ctx.guild)
                synced = []
            else:
                synced = await ctx.bot.tree.sync()

            await ctx.send(
                f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
            )
            return

        ret = 0
        for guild in guilds:
            try:
                await ctx.bot.tree.sync(guild=guild)
            except discord.HTTPException:
                pass
            else:
                ret += 1

        await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")

class Configuration(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
# PING CMD
    @commands.hybrid_command()
    async def ping(ctx, self):
        """ Replies with the Bot's latency """
        await ctx.send(f"Pong! {int(bot.latency*1000)}ms")

got this now - shows on the ping command that self is not accessed

willow sluice
dense falcon
boreal sigil
dense falcon
#

Awesome

boreal sigil
#

sync aint on there

#
class Configuration(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
# SYNC SLASH COMMANDS WITH <prefix>sync
    @commands.hybrid_command()
    @commands.guild_only()
    @commands.is_owner()
    async def sync(self, ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
        if not guilds:
            if spec == "~":
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "*":
                ctx.bot.tree.copy_global_to(guild=ctx.guild)
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "^":
                ctx.bot.tree.clear_commands(guild=ctx.guild)
                await ctx.bot.tree.sync(guild=ctx.guild)
                synced = []
            else:
                synced = await ctx.bot.tree.sync()

            await ctx.send(
                f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
            )
            return

        ret = 0
        for guild in guilds:
            try:
                await ctx.bot.tree.sync(guild=guild)
            except discord.HTTPException:
                pass
            else:
                ret += 1

        await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")

class Configuration(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
# PING CMD
    @commands.hybrid_command()
    async def ping(self, ctx):
        """ Replies with the Bot's latency """
        await ctx.send(f"Pong! {int(bot.latency*1000)}ms")
willow sluice
#

damn

dense falcon
boreal sigil
#

thats only rlly for slash commands

willow sluice
#

One day two geniuses met 🤦‍♂️🤦‍♂️

@boreal sigil You defined two classes with identical names

dense falcon
#

ohh i wasnt reading

#

you put all commands you want in one cog into the same class

#

So the ping command would go into the first Configuration class, then it would show both

boreal sigil
#

ok im confused sorry what?

#

how do i make it go into the first configuration class

willow sluice
#

@boreal sigil man its really annoying when people who havent learned python basics run to write discord bots and ask stupid questions

dense falcon
#

So basically take your ping command function, and move it into the first class called Configuration

boreal sigil
dense falcon
#

awesome

boreal sigil
#

now I do that for the rest of em

willow sluice
dense falcon
boreal sigil
fast osprey
boreal sigil
# dense falcon good luck :>
# COG: GAMBLE. ROLL, COINFLIP
class Gamble(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
# ROLL
    @commands.hybrid_command()
    async def roll(self, ctx, num: int):
        """ Rolls a random number """
        rollnum = random.randint(1, num)
        rng = discord.Embed(title=f"{ctx.author.display_name} rolled a {rollnum}",
                      colour=0x00f5f1)

        await ctx.send(embed=rng)
# COINFLIP
    determine_flip = [1, 0]
    @commands.hybrid_command()
    async def coinflip(self, ctx):
        """ Flips a coin """
        flipping = discord.Embed(title="A coin has been flipped...",
        colour=0x00b8f5)
        flipping.set_image(url="https://i.imgur.com/nULLx1x.gif")
        msg = await ctx.send(embed=flipping)
        time.sleep(3)
        if random.choice(determine_flip) ==1:
            heads = discord.Embed(title="A coin has been flipped...", description=f"The coin landed on heads!",
                            colour=0x00b8f5)
            heads.set_image(url="https://i.imgur.com/h1Os447.png")
            await msg.edit(embed=heads)
        else:
            tails = discord.Embed(title="A coin has been flipped...", description=f"The coin landed on tails!",
                            colour=0x00b8f5)
            tails.set_image(url="https://i.imgur.com/EiBLhPX.png")
            await msg.edit(embed=tails)

Bulbasaur_sigh

dense falcon
#

You should put determine_flip into the function, otherwise the code can't find it

boreal sigil
#

ah alright

#

it worked before outside of it, but oh well

dense falcon
#

sometimes things are weird

boreal sigil
#

yup - mess with code that works and get 1000 more errors

fast osprey
#

This is where OOP comes into play

scarlet tiger
boreal sigil
#

it worked fine before?

dense falcon
#

It works, but it can cause problems

quick gust
#

itll work fine for very short durations, u wont notice it

#

but its blocking

scarlet tiger
#

Yeah

boreal sigil
#

it seems to work

quick gust
#

read what I said again

dense falcon
#

If im correct that means that no other part of the script can be ran while the script is sleeping

boreal sigil
#

yeah ik but its blocking

quick gust
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries

  • The standard async library - asyncio
  • Asynchronous web requests - aiohttp
  • Talking to PostgreSQL asynchronously - asyncpg
  • MongoDB interactions asynchronously - motor
  • Check out this list for even more!
fast osprey
#

very short is misleading, as it's not only the number inside sleep but how many tasks will queue up behind it and add onto the issue

scarlet tiger
boreal sigil
#

so does this just fix it? await time.sleep(3)

#

nope it doesnt

quick gust
#

use asyncio

scarlet tiger
boreal sigil
#

thanks

#

works fine great

#

onto the next one

#

@dense falcon quick question how do you put spaces in a Cog name

#

eg. Channel Management

dense falcon
#

I believe there is an argument you can use to change the Cog's name to something like that, let me find it

boreal sigil
#

ah alright thanks

scarlet tiger
scarlet tiger
#

name="..."

boreal sigil
#

ah ok

scarlet tiger
boreal sigil
# scarlet tiger <:ducky_concerned:1178032077514477629>
# COG: Channel Management. LOCK, UNLOCK, HIDE, UNHIDE
class MyCog(commands.Cog, name="Channel Management"):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None
# LOCK
    @commands.hybrid_command()
    @commands.has_permissions(manage_channels=True)
    async def lock(ctx, channel : Optional[discord.TextChannel] = None):
        """ Locks the channel the command is used in, or a specified channel """
        channel = channel or ctx.channel
        overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
        if overwrite.send_messages is False:
            alreadylocked = discord.Embed(title="Error!", description=f"The channel is already Locked!",
                                    colour=0xf54242)
            await ctx.send(embed=alreadylocked)
            return
        overwrite.send_messages = False
        await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
        lock = discord.Embed(title="Channel Locked", description=f"The channel has been Locked!",
                        colour=0xe04d5c)
        await ctx.send(embed=lock)
        return

    @lock.error
    async def lock_error(ctx, error):
        if isinstance(error,commands.CheckFailure):
            await ctx.send('You do not have permission to use this command!')
        else: 
            raise error
quick gust
#

is there an error? do u need help? what are u asking

boreal sigil
#

the cog doesnt show up

#

wait-

#

IM SO DAMN STUPID-

scarlet tiger
boreal sigil
# scarlet tiger <:ducky_concerned:1178032077514477629>

so i forgot to register it. await bot.add_cog("Channel Management"(bot)) used this and it aint working.
error 1:
c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py:34: SyntaxWarning: 'str' object is not callable; perhaps you missed a comma? await bot.add_cog("Channel Management"(bot))
error 2:
Traceback (most recent call last): File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 449, in _run_event await coro(*args, **kwargs) File "c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py", line 34, in on_ready await bot.add_cog("Channel Management"(bot)) ^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'str' object is not callable

scarlet tiger
exotic hazel
#

Hello, I have a question about a distinction between a Discord bot vs a Discord app
#code-jam-participants-hangout message
This person says "you can use pure http interactions which doesn't require a Bot flow", would it make sense to learn that kind of thing before learning to make a bot? Is it easier?

fast osprey
#

You probably should start by looking at what you're trying to accomplish and then pick the best tool to accomplish it before considering what's easier

#

gateway bots are very good at doing a specific thing, but need to maintain websockets to do it

exotic hazel
#

I don't have a specific goal in mind yet, just curious if I should learn one thing before the other. Or if it doesn't matter which one I choose

fast osprey
#

They do accomplish different things

exotic hazel
#

Ok, I'll probably just start with a bot since I've seen more documentation on it

#

Thanks!

slate swan
#

Hello

#

I have a small problem pls , I have code source of a verification bot , the verification redirect normally to a site wich is for the original bot , the bot I have now I want that when the person click on verify he got redirected on the same site the original one , idk a lot abt coding so anyone can come in dm I screen share the code and tell me if the option is already in it ( I’m not the person who developed the bot btw ) and thank you 🙏

mild token
#
@commands.Cog.listener("on_member_update")
    async def on_member_update(self, before: discord.Member, after: discord.Member):
        print(before, after)
        pass

how will i know what changed ?, is by comparing is the only way?

fast osprey
#

Well what do you care about changing?

fast osprey
#

Are you just logging everything that could possibly change for the sake of logging it?

sick birch
sick birch
#

why not just use the audit log

#

its far better

#

unless you're trying to log something the audit log doesn't

mild token
sick birch
#

wdym

mild token
#

i mean adding emoji dont get logged in audit log

sick birch
#

so why not just log that

mild token
#

but d.py can get somehow

sick birch
#

and leave the rest to audit log

mild token
#

does message edit also get logged in audit log?

finite salmon
pseudo geode
#

need help my bot and command etc now works but I have to press run every minute or so how do I fix it so it just runs?or at least for a while longer?

#

@ me if yk how to fix

fast osprey
#

Where are you running it?

pseudo geode
torn solar
#
def setup_news_commands(bot):
    news_group = app_commands.Group(name="news", description="News related commands")
    
    def has_staff_role(ctx):  # Function to check if user has any staff role
        # Fetch the member to ensure roles are up-to-date
        member = ctx.guild.get_member(ctx.author.id)
        if not member:
            return False
        user_roles = [role.id for role in member.roles]
        matching_roles = [role_id for role_id in staff_roles if role_id in user_roles]
        if matching_roles:
            return True
        else:
            return False
    
    @news_group.command(name="setreviewchannel", description="Set review channel for news articles.")
    @commands.check(has_staff_role) 
    async def news_setreviewchannel(interaction: discord.Interaction, channel: discord.TextChannel):
        
        try:
            with open('main.json', 'r') as f:
                data = json.load(f)
        except FileNotFoundError:
            data = {}

        data['review_channel_id'] = channel.id

        with open('main.json', 'w') as f:
            json.dump(data, f, indent=4)

        await interaction.response.send_message(f'Review channel set to {channel.mention}')``` command works fine but even though someone doesnt have one of the staff roles they can still do the command
#

no errors

fast osprey
#

You should consider using the integrations menu to limit app commands rather than checking locally in code

granite shadow
#

Hello
I have a bot and when this bot is used I just want the user to see his command, I have almost no knowledge on how to do it.

torn solar
#

do you have any idea why thats not working?

torn solar
willow sluice
#

I dont understand what your code does

torn solar
#

its a group commands named 'news'

#

the commands work fine but the permission check isnt working

willow sluice
#

first of all i guess you need to use

#

!d discord.app_commands.check

unkempt canyonBOT
#

@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.

These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure) exception is raised and sent to the appropriate error handlers.

These checks can be either a coroutine or not.

Examples

Creating a basic check to see if the command invoker is you...
willow sluice
#

is is working right now?

torn solar
#

just added it gonna check

#
Task exception was never retrieved
future: <Task finished name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() done, defined at /home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py:1149> exception=AttributeError("'Interaction' object has no attribute 'author'")>
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1151, in wrapper
    await self._call(interaction)
  File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1310, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 879, in _invoke_with_namespace
    if not await self._check_can_run(interaction):
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 1017, in _check_can_run
    return await async_all(f(interaction) for f in predicates)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.12/site-packages/discord/utils.py", line 704, in async_all
    for elem in gen:
  File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 1017, in <genexpr>
    return await async_all(f(interaction) for f in predicates)
                           ^^^^^^^^^^^^^^
  File "/home/container/commands/news.py", line 15, in has_staff_role
    member = ctx.guild.get_member(ctx.author.id)
                                  ^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'author'``` well it seems to be working but if i dont have the role it throws this error
#

@willow sluice

#
@news_group.command(name="remove", description="Remove a news registration")
    @app_commands.check(has_staff_role) 
    async def news_remove(interaction: discord.Interaction, channel_id: str):
        ensure_json_file('channels.json')

        with open('channels.json', 'r') as f:
            channels = json.load(f)

        if channel_id in channels:
            user_channel = bot.get_channel(int(channel_id))
            guild_name = user_channel.guild.name
            news_channel = bot.get_channel(news_channel_id)
            del channels[channel_id]
            with open('channels.json', 'w') as f:
                json.dump(channels, f, indent=4)
            await interaction.response.send_message(f"Channel ID {channel_id} has been successfully removed.")
            await news_channel.send(f"**{guild_name}** - <#{channel_id}> has been removed from the newsfeed!")
        else:
            await interaction.response.send_message(f"The specified Channel ID was not found.")```
willow sluice
#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
willow sluice
#

AttributeError: 'Interaction' object has no attribute 'author'

granite shadow
#

not for everyone

#

wait

willow sluice
#

@torn solar i agree its very difficult to write code YOURSELF

def has_staff_role(interaction: discord.Interaction):
    return bool([i for i in staff_roles if i in interaction.user.roles])
willow sluice
granite shadow
#

app one

#

im new in python

#

i just write this code

#

@tree.command(name='kaydol',
description="Kaydolmak için kullanılır [kullanıcı_adı] [şifre]")
async def kaydol(interaction: discord.Interaction, kullanıcı_adı: str,
sifre: str):
f = open("keys.txt", "a")
f.write(f" | {kullanıcı_adı}, {sifre} | ")

em = discord.Embed(description=f"Başarıyla kaydolundu!", color=0x0025ff)
await interaction.response.send_message(embed=em)

#

its turkish

willow sluice
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None, poll=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
willow sluice
#

read docs

granite shadow
#

thanks

#

i will try

willow sluice
#

there is arg what you are looking for

granite shadow
#

i hope

willow sluice
#

this is statement and not question you will find it

granite shadow
#

how i made this type of message

#

?

willow sluice
#

this is default error when interaction didnt response

granite shadow
#

yea ik

#

i just want to show you this i need to my bot type like that only i see

#

i need the "Only you cann see this" thing

willow sluice
#

i got what you want and i send you link to docs

granite shadow
#

oh okay

#

thanks im trying to find tmrw

willow sluice
#

Can you read? There are only 10 lines

#

im really surprised by you and people like you its anoying

granite shadow
torn solar
# willow sluice Can you read? There are only 10 lines
def setup_news_commands(bot):
    news_group = app_commands.Group(name="news", description="News related commands")
    
    def has_staff_role(interaction):  # Function to check if user has any staff role
        # Fetch the member to ensure roles are up-to-date
        member = interaction.guild.get_member(interaction.user.id)
        if not member:
            return False
        user_roles = [role.id for role in member.roles]
        matching_roles = [role_id for role_id in staff_roles if role_id in user_roles]
        if matching_roles:
            return True
        else:
            embed = discord.Embed(title="No Permission", color=d_color, description="""
                                  You do not have permission to execute this command!""")
            interaction.response.send_message(embed=embed)
            return False
    
    @news_group.command(name="setreviewchannel", description="Set review channel for news articles.")
    @app_commands.check(has_staff_role) 
    async def news_setreviewchannel(interaction: discord.Interaction, channel: discord.TextChannel):
        
        try:
            with open('main.json', 'r') as f:
                data = json.load(f)
        except FileNotFoundError:
            data = {}

        data['review_channel_id'] = channel.id

        with open('main.json', 'w') as f:
            json.dump(data, f, indent=4)

        await interaction.response.send_message(f'Review channel set to {channel.mention}')
``` the check is working although its not sending the embed saying no permission and if they dont have the permission it throws an error in console so how can i handle it correctly
#
  File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1310, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 880, in _invoke_with_namespace
    raise CheckFailure(f'The check functions for command {self.name!r} failed.')
discord.app_commands.errors.CheckFailure: The check functions for command 'remove' failed.``` this is the error
fast osprey
#

So one thing you could do is limit this on permission and have individual guilds choose if they want a specific role. What you have now is pretty inflexible if people decide they want to change things, and plus it still lets users see the command when you could prevent them from running it in the first place

torn solar
#

i have the permissions working

#

i just need to know how to handle the error

fast osprey
#

I mean you do you, but discord has given you a system for managing permissions, and you're writing extra code to go around it

willow sluice
#

you will be very surprised when you find out how much useful information is in google and discord.py docs

torn solar
wild gate
#

import discord

from discord.ext import commands

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

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

@client.command()
async def hello(ctx):
await ctx.send("hello, world")

client.run('TOKEN')
anyone have any idea why I'm getting invalid syntax, chatgpt isn't giving really a reason

willow sluice
#

there should be error in console pointing to line

wild gate
#

it says line 1

#

but like it's just importing discord

willow sluice
#

give me screenshot of error

wild gate
#

nvm it was in python mode for the terminal

#

dk how that happened but ye

willow sluice
#

💀

fervent surge
#

quick question: is d.py still the most popular framework? Or are forks now more popular?

wild gate
#

how would I get it the bot to actually print out "hello, world" into the chat?

#

like do I do /hello?

#

or !hello?

#

how tf do i shut down a bot

#

nvm it's ?hello

fast osprey
#

This would result in a warning

wild gate
#

it doesn't 🤷

torn solar
#
async def on_error(self, interaction: discord.Interaction, error: discord.app_commands.AppCommandError):
        if isinstance(error, discord.app_commands.errors.CheckFailure):
            embed = discord.Embed(title="No Permission", color=d_color, description="""
                                  You do not have permission to execute this command!""")
            await interaction.response.send_message(embed=embed,ephemeral=True)
        else:
            raise error``` tried to do this to handle this error below
```Traceback (most recent call last):
  File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1310, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 880, in _invoke_with_namespace
    raise CheckFailure(f'The check functions for command {self.name!r} failed.')
discord.app_commands.errors.CheckFailure: The check functions for command 'remove' failed.``` but its still not handling the error
hushed galleon
torn solar
# hushed galleon how did you add your error handler to the tree?
class DemocracyUtilsBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.all()
        super().__init__(command_prefix="?!", intents=intents)

    async def on_ready(self):
        print(f'Logged in as {self.user}')
        await self.change_presence(activity=presence, status=status)
        setup_news_commands(self)  # Setting up news commands

    async def on_message(self, message):
        # Process message here
        await self.process_message_for_webhook(message)
        await self.process_commands(message)
        
    async def on_error(self, interaction: discord.Interaction, error: discord.app_commands.AppCommandError):
        if isinstance(error, discord.app_commands.errors.CheckFailure):
            embed = discord.Embed(title="No Permission", color=d_color, description="""
                                  You do not have permission to execute this command!""")
            await interaction.response.send_message(embed=embed,ephemeral=True)
        else:
            raise error``` its inside my bot class
hushed galleon
#

oh, Bot.on_error isnt the same as the tree's on_error

#

i'd suggest naming your method to something else and then using self.tree.error() to register it on your tree, e.g. ```py
class MyBot(commands.Bot):
def init(self):
super().init(...)
self.tree.error(self.on_tree_error)

async def on_tree_error(self, interaction, error):
    ...```
torn solar
#

ill try this

torn solar
#

this worked btw forgot to respond ty

quick gust
#

(disnake) what flow of interactions should I use if I am sending a View in my message and later need to set a message attr to the view (so that I can disable the view on timeout and edit the message with the updated view)

#
class PaginatorView(disnake.ui.View):
    message: disnake.Message

    async def on_timeout(self) -> None:
        for child in self.children:
            child.disabled = True
            
        await self.message.edit(view=self)

basically what I'm asking is how should I respond to the slash command interactions to be able to get the disnake.Message object

willow sluice
finite salmon
#

And when sending the view attach the message object there

#
view = PaginatorView()
msg = await ctx.send(view=view)
view.message = msg
#

Something like this

quick gust
#

That's what I'm doing, my question is how to get the msg object u used here, with slash commands

#

I'm not good with slash commands

finite salmon
#

interaction.message

#

instead of view.message = msg, pass in interaction.message

quick gust
#

I'll test it once I can, thanks

limber jolt
#
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')

    try:
        await bot.load_extension('cogs.shift')  
        await bot.load_extension('jishaku')
        await bot.load_extension('cogs.fun')
        await bot.load_extension('cogs.utility')
        await bot.load_extension('cogs.moderation')
      
        print('Cogs loaded successfully')
    except Exception as e:
        print(f'Failed to load cog: {e}')```
#

Error: Failed to load cog: No module named 'cogs'

slim bloom
limber jolt
slim bloom
limber jolt
slim bloom
limber jolt
simple zinc
#

hey , how can i get info about another user , other than the author of the command ? like !command @mention , so i should get , info about both , author and the user the author mentioned

limber jolt
# simple zinc hey , how can i get info about another user , other than the author of the comma...
    async def serverinfo(self, ctx):
        guild = ctx.guild
        embed = discord.Embed(title="Server Info", description=f"Information about {guild.name}", color=0x00ff00)
        embed.set_thumbnail(url=guild.icon.url)
        embed.add_field(name="Server Name", value=guild.name, inline=True)
        embed.add_field(name="Server ID", value=guild.id, inline=True)
        embed.add_field(name="Owner", value=guild.owner, inline=True)
        embed.add_field(name="Region", value=guild.region, inline=True)
        embed.add_field(name="Members", value=guild.member_count, inline=True)
        embed.add_field(name="Roles", value=len(guild.roles), inline=True)
        embed.add_field(name="Channels", value=len(guild.channels), inline=True)
        embed.add_field(name="Created At", value=guild.created_at.strftime("%Y-%m-%d %H:%M:%S"), inline=True)
        await ctx.send(embed=embed)```
simple zinc
#

thx for the help , let me try and understand that

hearty basalt
limber jolt
#
    async def userinfo(self, ctx, member: discord.Member = None):
    
        member = member or ctx.author
        embed = discord.Embed(title="User Info", description=f"Information about {member}", color=0x00ff00)
        embed.set_thumbnail(url=member.avatar.url)
        embed.add_field(name="Username", value=member.name, inline=True)
        embed.add_field(name="Discriminator", value=member.discriminator, inline=True)
        embed.add_field(name="ID", value=member.id, inline=True)
        embed.add_field(name="Status", value=member.status, inline=True)
        embed.add_field(name="Top Role", value=member.top_role.mention, inline=True)
        embed.add_field(name="Joined Server", value=member.joined_at.strftime("%Y-%m-%d %H:%M:%S"), inline=True)
        embed.add_field(name="Account Created", value=member.created_at.strftime("%Y-%m-%d %H:%M:%S"), inline=True)
        await ctx.send(embed=embed)```
#

This iS how to get user Info

#

The other one was server

simple zinc
simple zinc
limber jolt
#

For yours

#

As Im using cogs without the @bot stuff.

simple zinc
#

ya , i will do that , and i should also remove the self parameter

limber jolt
hearty basalt
#

fair

limber jolt
simple zinc
hearty basalt
#

👍

simple zinc
#

thx i understood most of it

#

can i explain this member:discord.Member:None whats None parameter does in it

#

Represents a Discord member to a Guild.

This implements a lot of the functionality of User.

Attributes
joined_at: Optional[datetime.datetime]
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
activities: Tuple[Union[BaseActivity, Spotify]]
The activities that the user is currently doing.

simple zinc
#

me*

hearty basalt
#

it means the argument is optional

#

member: discord.Member = None

#

i think

timber dragon
#

It's the same thing as doing : discord.Member | None = None in dpy

#

But you can default to the command author here instead of None and handling it in the callback:

member: discord.Membed = commands.Author
granite shadow
#

how i get the user id with tree command?

timber dragon
#

Interaction.user is an instance of Member/User

granite shadow
#

thankss

granite shadow
fast osprey
#

What is this txt file being used for?

dense falcon
slate swan
wanton current
#

needs a prefix

slate swan
#

and how do i do that

wanton current
#

add a command_prefix= parameter

granite shadow
wanton current
#

make it a string and remove the parenthesis

slate swan
#

how i make it a string

wanton current
#

command_prefix="!"

slate swan
dense falcon
slate swan
#

i js added

dense falcon
#

Show where you're putting the code

slate swan
dense falcon
#

you'll want something like this:
bot = MyBot(command_prefix='!', intents=intents)

#

You ended up defining bot twice

granite shadow
slate swan
dense falcon
#

Well firstly for your deleted screenshot, Slash Commands are referred to as app_commands

slate swan
#

k

#

done

dense falcon
#

uh can you show the code that's having the error

slate swan
#

``@bot.app_commands(guild_ids=[settings["guildID"]], name="whitelist", description="Whitelist a person to use the bot.")
async def whitelist(ctx: discord.ApplicationContext,
user: discord.Option(discord.Member, "Member to whitelist.", required=True)):
if not isAdmin(ctx):
return await ctx.respond("Only Bot Admins can use this command.")

settings["botWhitelistedId"].append(str(user.id))
json.dump(settings, open("settings.json", "w", encoding="utf-8"), indent=4)

return await ctx.respond(f"*{user.mention} has been whitelisted.*")``
dense falcon
#

what's the code for settings? how is it defined

slate swan
#

``{
"capmonsterKey": "CAP-25C663138AF0088A8990B793EF92B0B1",
"botToken": "Token",
"guildID": "1260963242428207284",
"botAdminId": [
"741839840110182441"
],
"botWhitelistedId": [

]

}``

granite shadow
#

Uh its not working :(

dense falcon
granite shadow
#

no no

#

wait a sec

dense falcon
granite shadow
#

i want to create this txt file in to a users folder

granite shadow
dense falcon
#

f"users/{member}.txt"?

granite shadow
#

ohh

#

i just think it like folder or file.txt

#

my bad sorry

dense falcon
#

what do you want it to do?

slate swan
#

guild id

#

to use my servers guild id to connect the bot online

dense falcon
#

yes, but what do you want to achieve from it

#

fuck wait nvm

slate swan
#

its a boost bot

dense falcon
#

whats that

slate swan
#

js a bot

#

like i want the guild id to make it go online

dense falcon
#

the closest I can think of for this is you want the bot's slash commands to work in the guild

slate swan
#

yes

dense falcon
#

ok remove the guild_ids parameter in the decorator

slate swan
#

in settings?

dense falcon
#

@app_commands.guilds(discord.Object(id=GUILD_ID_GOES_HERE))

dense falcon
#

app_commands

slate swan
#

im confused, can u help me if i send the code?

fast osprey
#

What are you trying to do with this parameter

#

by default app commands are global and available to all guilds the bot is in

dense falcon
#

you see this
@bot.app_commands(guild_ids=[settings["guildID"]], name="whitelist", description="Whitelist a person to use the bot.")

#

change it to this
@bot.app_commands(name="whitelist", description="Whitelist a person to use the bot.")

#

successfully removed guild_ids parameter

slate swan
dense falcon
fast osprey
#

It doesn't

wanton current
#

what is bot.app_commands?

dense falcon
fast osprey
#

There used to be a delay on global syncing more than a year ago

wanton current
#

use @bot.tree.command()

dense falcon
#

I use hybrid commands so I kinda forgor the rest

wanton current
#

there's also @app_commands.command

dense falcon
#

ah that's the one

mild token
#

is there a way to ensure task loop only start after the bot start?

neat field
#

so if i understand correctly the major differences between REST api and gateway is

  • REST api only revices interaction events
  • Gateway api can receive all intents that the bot is registred for
  • REST api does not need a always alive connection
  • purely interaction based "apps" can be made in both http and gateway

is this all ?

mild token
unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
mild token
#

this thing

#

when my bot loads sync loop starts before on_ready

#

as i am calling it on constructor is there a way to ensure it only starts after on_ready?

scarlet tiger
mild token
fast osprey
#

wait_until_ready is a utility that yields until the bot is ready. Nothing calls it, you would use it in some task you wanted to wait

scarlet tiger
fast osprey
#

There's a very common pattern to await wait_until_ready inside of a task loop's before_loop. Then you can start it wherever you want

#

in fact, this is done in one of the recipes in the official docs

mild token
quick gust
#

in before_loop

mild token
mild token
fast osprey
#

Code? These are just a bunch of log statements you're making

mild token
#

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

mild token
#

sorry for bad code : (

fast osprey
#

What do you mean by "api fetching"?

mild token
fast osprey
#

Which is?

#

What in the above screenshot is wrong?

mild token
fast osprey
#

You should not be using on_ready to drive logic

mild token
#

so bot have all the things in its cache

mild token
#

wait_until_ready this thing

fast osprey
#

You just said you wanted on_ready to fire. Why do you care about that event

#

You're using wait until ready. That will yield after the cache is populated. What makes you think it isn't?

mild token
fast osprey
#

Again. On_ready is not what you want or care about here

mild token
#

i thought bcz of log statement

#

ty for clarification

fast osprey
#

When the cache is populated, a few things happen and the ordering of them isn't guaranteed

#

on_ready will fire but not necessarily before or after wait_until_ready yields

mild token
#

actually what i am doing is , i am hitting api every 5 minutes if the data change i changes role according to that so when bot gets online and it checks sometimes it doesnt remove the roles

fast osprey
#

What api?

mild token
#

its a private game api developed by my friend

fast osprey
#

Ah. Ideally they'd implement a pubsub method to reduce load for both of you but for private stuff it's whatever

mild token
#

what's pubsub?

#

sorry i dont know about that : (

fast osprey
#

You subscribe to this service, and it pushes relevant changes to you

#

Rather than you having to ask every 5 minutes

mild token
#

i will definately look into this

#

really looks like a neat concept

fast osprey
#

It's advanced and not needed on this scale probably but interesting to learn

granite shadow
#

how to make a inventory system without mangodb? i just coded little but its not working

fast osprey
#

If you're tracking dynamic data generated by your application, you absolutely should be using a database and not writing to flat files yourself

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

limber jolt
#

How do I do that type of text?

#

The bottom one

midnight oracle
# limber jolt

any feedback would be helpful

i know

it's not the same

but i have no clue how to do that xd
testing text i guess

limber jolt
midnight oracle
#

any feedback would be helpful
-# This user Is suspected of pirating music online

limber jolt
#

-# t

finite salmon
#

Discord mobile can't render it tho lol

somber sky
#

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

somber sky
#

https://paste.pythondiscord.com/5ZTA

Traceback (most recent call last):
await item.callback(interaction)
await self.show_page(interaction)
message = await interaction.response.edit_message(embed=embed)
AttributeError: 'Button' object has no attribute 'response'

im lowkey rusty at coding but i remember this used to happen when trying to edit messages/embeds with buttons involved but idk how to fix it

fast osprey
#

You are most likely using dpy as a library while following a tutorial made for another library

wild gate
#

if I use nextcord instead of discord.py will I still be able to use all of the regular discord.py functions?

#

cuz I'm getting this:
DistributionWarning: discord.py is installed which is incompatible with nextcord. Please remove this library by using pip3 uninstall discord.py

fast osprey
#

You should pick one

wild gate
#

will I still be able to use like
@client.command()
@commands.is_owner()
async def shutdown_bot(ctx):
await ctx.send("Shutting down...")
print("Shutting down...")
await client.close()

sick birch
#

it may be a bit different

wild gate
#

or do I have to figure out how to do it in nextcord

wanton current
#

should since it's a d.py fork

sick birch
#

but nextcord is a fork so the commands stuff should be mostly the same

fast osprey
#

Can't tell you how much forks have diverged, or how much they will continue to diverge

sick birch
#

from what i can tell the interactions stuff differs a fair bit more

wild gate
#

ok

sick birch
#

you will have to read the docs and figure that out

wild gate
#

thanks

somber sky
#

https://paste.pythondiscord.com/QLRA

Can someone help me put pagination on this? I've been trying for a couple of hours but it just keeps giving me error so i restarted it without the pagniation

fast osprey
#

Error?

somber sky
fast osprey
#

Also, app commands do not receive a context. You should not be calling the parameter ctx

somber sky
fast osprey
#

Are you logging anything?

#

There is code here which would definitely cause an error

#

And when you say you get interaction failed, that happens when?

somber sky
somber sky
fast osprey
#

Then send the view code please

#

this is a command

somber sky
fast osprey
#

But you're saying the failure is happening with a button

fast osprey
#

and start from those

somber sky
fast osprey
#

You did not

#

Your view looks different from the examples. You should START from the examples, not try and pinpoint differences off of whatever you started with

somber sky
fast osprey
#

You started with examples/tutorials someone made for another library

obsidian dune
#

does anyone have a GitHub link to a working up to date multipurpose bot that i could directly clone into vs code and add a token and run?

wanton current
#

maybe redbot

obsidian dune
#

bedsides redbot?

obsidian dune
wanton current
#

can just search with the discordbot tag on github

willow sluice
#

@obsidian dune

import discord
from discord.ext import commands

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

@bot.event
async def on_ready():
    print(f'We have logged in as {bot.user}')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    await bot.process_commands(message)

@bot.command()
async def hello(ctx):
    await ctx.send('Hello!')

bot.run('token')
wanton current
#

very multipurpose

willow sluice
#

It even has a hello command

#

Imagine

obsidian dune
#

wowo

obsidian dune
tired star
#

is it normal that when syncing slash commands in takes a long time before it appears on discord?

fast osprey
#

Nope it's basically instant

#

Sometimes you have to reload your client, or you're not syncing what you think you are

craggy anvil
#

Hello, i have this code:

@bot.event
async def on_guild_channel_create(channel, ctx):
    # Check if the channel name starts with "bitcoin", "litecoin", or "eth"
    if channel.name.lower().startswith(("bitcoin", "litecoin", "eth")):
        unique_id = f"zxczxczxc"
        await ctx.send(unique_id)
        asyncio.sleep(1)
        await ctx.send("Send us user id of guy you're dealing with!")```

How should i add bot.event to detect next message that user will send(User id), if it's valid user id from server then overwrite his permissions to read and send messages in channel
#

dont mind unique id i wrote it manualy for sending it here because it was messing up backsticks message

golden portal
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError) for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple) containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
golden portal
#

see the example in the docs there for waiting for a message

slate swan
#

having a problem getting to use prefix and slash commands onto the same bot

mild token
slate swan
#

i have slash commands but the prefix commands dont work for some reason

mild token
#

It will only work for slash

slate swan
#

i have it like this

@bot.tree.command(name="test")

mild token
#

Yeh u r adding it to tree

#

Remove tree and then try

slate swan
#

ye i want slash and prefix also

mild token
#

For same command?

slate swan
#

no

#

different names

mild token
#

Then don't add that to tree then it should work i belive ,I have not tried it myself but it should work iirc

slate swan
#

alright

mild token
#

If u add that to tree then I belive it will be added to slash category

vocal laurel
#

it is the same command but can be slash or prefix

limber jolt
#

I need some help I have loads of cogs but when I load them I get a error saying the folder does not exist.

#

Wait

#

Nvm I fixed It

trim oriole
#

hi

#

how is a interaction different from commands

limber jolt
trim oriole
#

which display userinfo formatted

limber jolt
#

They are the same thing

#

type /

#

and you can see slash commands

trim oriole
#

i thought interaction performs a certain task for us?

#

rather than output

limber jolt
#

You cant do that for commands

limber jolt
#

Or I dont think

#

I dont rlly user interactions

trim oriole
#

like if i do /ping

#

how is slash commands different from like if i make a command using Command and make command_prefix /

#

or is there a class for slash commands

hearty basalt
drowsy thunder
#

Anyone wanna join a bot team dm me 🙂

fast osprey
#

There's a whole list of things that slash commands support which prefix don't and vice versa. They are two separate systems with different behavior really

grand moss
#

not sure I understand this

#

works for the other prefix commands

#

this is the whole thing:

#help/list command
@bot.command()
async def help(ctx):
  embed=discord.embed(
    colour=discord.Colour.blue(),
    description="\n1. ping\n2. hi\n3. hello\n4. inspire\n5. dog\n6. cat",
    title="Command List",
    timestamp=current_time
  )
  await ctx.send("\n", embed=embed)
#

nvm got it, changed help to command

fast osprey
#

dpy bots ship with a default help command

#

Probably does what you want but cleaner. You can augment it if you want to change how it displays

grand moss
#

hmm, would you happen to know where I can read up more

fast osprey
#

Other option being moving to slash commands which are largely self documenting

grand moss
#

thanks a lot, I'll go through this

slate swan
#

reaf my discryption

fast osprey
young dagger
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id

#
@client.command(name='testban')
@commands.guild_only()
async def testban(ctx, member: discord.User = None):

    try:
        server_ban = await ctx.guild.fetch_ban(member.id)
        if server_ban:
            await ctx.send("Found banned user.")
    except discord.NotFound:
        await ctx.send("User is not banned from the server.")
fast osprey
#

!d discord.Guild.fetch_ban

unkempt canyonBOT
#

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

Retrieves the [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry) for a user.

You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members) to get this information.
young dagger
fast osprey
#

Yes, and the reviewing the documentation for the method you're using should make it clear what the issue is

fast osprey
#

Read the documentation, and check the expected inputs and outputs

#

compare what you are passing into the method with what the documentation says you should be

fast osprey
#

So

  • What are you passing into fetch_ban
  • What does the documentation say you should be
young dagger
fast osprey
#

It does not

#

Review the Parameters section of that method

#

It tells you the type it wants

young dagger
#

user (abc.Snowflake)

fast osprey
#

Yes. That is not an integer

young dagger
dense falcon
#

You'd want to get a user from the ID using get_user() or fetch_user()

#

then put that into fetch_ban

fast osprey
#

Snowflake is a type. It isn't just a fancy way of calling an integer

#

(You already have a Snowflake)

#

They don't need to get or fetch a user, given they already have one

dense falcon
#

ah yeah pass member into it or smth

young dagger
#

ctx.guild.fetch_ban(member)

dense falcon
#

I'd try it ye

young dagger
#

Could I also use something like ctx.guild.fetch_ban(discord.Object(member.id))

dense falcon
#

probably, but why?

young dagger
#

Or that would be the same as member

dense falcon
#

that would be the same as member

#

since member is a discord.User, getting the object with member's ID would just return the same user

young dagger
#

Oh, I see thanks. I'm still confused why it says to use Snowflake, and when I do it gives me an error?

fast osprey
#

Snowflake is a base type. It's just a holder for a discord object id. Other types (like user, member, channel, guild) implement it

young dagger
fast osprey
#

You weren't. The library was. It was expecting you to give it a Snowflake, which it would assume has a .id attribute

young dagger
#

Mhm

craggy anvil
#

how should i use discord.py to add buttons to my discord embed, didnt code bots for long now, and my bot got verified not long ago so i have to hop on updates 🙂

wanton current
#

there's button examples in the repo

craggy anvil
#

An error occurred: expected Item not tuple

#
            if user:
                await channel.set_permissions(user, read_messages=True, send_messages=True)
                await channel.send(f"@{user}")
                embed = discord.Embed(title="Example Embed", description="This is an example embed with buttons", color=0x37f563)

                view = discord.ui.View()

                style = discord.ButtonStyle.gray
                styledanger = discord.ButtonStyle.danger

                item = discord.ui.Button(style=style, label="Sender"),
                item1 = discord.ui.Button(style=styledanger, label="Receiver"),
                item2 = discord.ui.Button(style=style, label="Reset")

                view.add_item(item=item)
                view.add_item(item=item1)
                view.add_item(item=item2)
                await channel.send(embed=embed, view=view)```
#

What's up with this error huh

somber sky
#

when im pulling/pushing from vscode to github and i have databases that i edited do i just not do it or what

quick gust
#

just not do what?

hushed galleon
#

!e py x = "Hello world!", print(x)

unkempt canyonBOT
craggy anvil
#

Oh so item = blabla,
Item1= blabla,
item2 = blabla

#

Right?

hushed galleon
#

yeah, those trailing commas are the cause

#

also i would suggest defining buttons using the decorator style instead, that'll make it easier to write callback functions for them: ```py
class MyView(discord.ui.View):
@discord.ui.button(label="Greet", style=discord.ButtonStyle.primary)
async def greet(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message(f"Hello there, {interaction.user.mention}!")

To use:

view = MyView()
await channel.send(..., view=view)```

craggy anvil
#

Ohh will keep in mind

median radish
#

i would really like someone

#

to teach me on how to learn python and discord bots and tools etc

#

whoever is very advanced and has day to day time to teach i will really appreciate it, small payment at the end

fast osprey
#

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

median radish
#

@fast osprey

fast osprey
#

Well that's not very nice

median radish
fast osprey
median radish
#

to learn

fast osprey
#

Well for starters, I had 7 years of industry python experience under my belt

median radish
fast osprey
#

I started by learning programming fundamentals, which I did at a 4 year full time university

median radish
#

im looking for basic python lessons for starters, tips i am looking for

median radish
#

how old is u my boy 💀

fast osprey
#

Pretty probing question from an online rando

median radish
#

dont make it weird yert

fast osprey
#

I'm not the one doing anything, trust me

median radish
#

just where did u go to learn fundamentals

median radish
fast osprey
#

From university courses and text books

median radish
#

so u cant learn it online?

#

all i really want to know is how to make like discord bots and databases and shi

fast osprey
#

And you will need programming and python fundamentals before you do that

#

the official python docs are pretty good, though they do rely on some base programming knowledge

median radish
#

and what is minimum age to learn all this. can u learn at a young age

fast osprey
#

Googling python docs is a good start

median radish
fast osprey
#

These concepts build on top of each other and take time to learn, so if you're starting from scratch this is an investment

median radish
#

I am learning so much LOL

median radish
midnight herald
#

This may be a super silly question but. Is it by any chance possible to make a bot that can edit google sheets?

#

Or at the very least, read and take the values of a google sheet?

wanton current
#

yeah

midnight herald
#

Then, is it possible to make it so the bot can edit one google sheet using the values of another google sheet? (Lets say member 1 uses their own sheet to use a command that changes the values of member 2’s cell d:6 using the value of member of member 1’s cell d:4. Or maybe even a formula using said values?)

wanton current
#

i dont see why not

#

use the google docs api

midnight herald
#

Mkay.

young dagger
void mauve
#

Is there a way to find out inviter user id of the specific user in the guild besides scraping the whole response from https://discord.com/api/v9/guilds/{guild_id}/members-search?

drifting arrow
#
    @app_commands.command(name="testcommand", description="A Test command")
    @guild_only()
    async def testcommand(self, interaction:Interaction, user_input_1:str, user_input_2:int) -> None:
        await interaction.response.send_message("Hello World")

What would be the javascript equivalent to this? My friends trying to make a bot in javascript and IDK javascript ;-; im hoping someone here can help lol

fast osprey
#

Asking how to make something in js really isn't in the remit for the Python server

mild token
#

Is it possible to find with whose invite someone joined?

#

Or is it by a vanity url?

violet crow
#

ctx.guild.members returns list of all members?

merry cliff
#

yes

#

It might need the server memb ers intent

limber jolt
#

My cogs dont work help

sick birch
#

unless you're doing some sort of leaderboard tracking thing

sick birch
limber jolt
sick birch
#

does your input cog have a setup function?

limber jolt
sick birch
#

can you show the whole code

limber jolt
#
from discord.ext import commands

# Create a bot instance with a command prefix
bot = commands.Bot(command_prefix='!')

# Dictionary to store log channels per server (guild)
log_channels = {}

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

    @commands.command()
    async def logchannel(self, ctx, channel_id: int):
        # Try to fetch the channel by ID
        channel = self.bot.get_channel(channel_id)
        if channel:
            # Store the log channel for the current guild
            log_channels[ctx.guild.id] = channel_id
            await ctx.send(f'Log channel has been set to {channel.mention}')
        else:
            await ctx.send('Invalid channel ID. Please provide a valid channel ID.')

    @commands.command()
    async def log(self, ctx):
        # Get the log channel for the current guild
        channel_id = log_channels.get(ctx.guild.id)
        if channel_id:
            channel = self.bot.get_channel(channel_id)
            if channel:
                await channel.send('A log has been created.')
            else:
                await ctx.send('Log channel not found.')
        else:
            await ctx.send('Log channel is not set. Use !logchannel <channel_id> to set it.')

async def setup(bot):
    await bot.add_cog(input(bot))```
sick birch
#

where is your bot.load_extension

limber jolt
# sick birch where is your `bot.load_extension`
from discord.ext import commands
import sqlite3


# Database setup
conn = sqlite3.connect('shifts.db')
cursor = conn.cursor()


# Bot setup
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

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

    try:
        await bot.load_extension('cogs.shift')  
        await bot.load_extension('jishaku')
        await bot.load_extension('cogs.fun')
        await bot.load_extension('cogs.utility')
        await bot.load_extension('cogs.moderation')
        await bot.load_extension('cogs.input')
        print('Cogs loaded successfully')
    except Exception as e:
        print(f'Failed to load cog: {e}')

bot.run('Token')``` This is In my bot.py
limber jolt
hushed galleon
#

this is with discord.py 2.0 right? weird that it didnt tell you a different error since the commands.Bot(command_prefix='!') declaration inside your extension module should have raised a TypeError for missing the intents= argument

sick birch
#

yeah i'm not sure it's 2.0

#

it would explain the setup function not found

#

though, shouldn't it say it's not a function or similar?

#

@limber jolt can you get us your discord.py version?

sick birch
hushed galleon
#

but if it was able to load the other extensions without that error, it likely is dpy

limber jolt
#

discord.py or discord?

hushed galleon
#

in which case there should have been a different exception for failing to load the module, so perhaps input.py just isn't saved?

limber jolt
hushed galleon
#

do you have any other libraries like nextcord or py-cord? those would conflict too

limber jolt
limber jolt
#

SOrry If I sound stupid just woke up

sick birch
#

you may wanna double check, if you aren't using a venv it can conflict from other projects if you installed another library in the past

#

pip list lists all packages

hushed galleon
#

discord might be a mirror of discord.py, but they overwrite each other's files which can occasionally result in some obscure bugs

mild token
limber jolt
dusky pine
#

mfw you pip installed discord.js

limber jolt
mild token
#

Is it possible to accept attachment with slash commands? Or any other attachment?

limber jolt
sick birch
#

i think slash commands do support attachments

dusky pine
mild token
#

It will be in bytes format right?

sick birch
#
from discordjs import Client
from javascript import console

client = Client()

client.on("ready", lambda:
    console.log("Bot is ready")
)

async def msg(message):
    if message.content.startswith("!ping"):
        await message.channel.send("pong")

client.on("message", msg)

client.login('Token')
#

this is kind of funny

#

someone tried to recreate discord.js in python

hushed galleon
#

dont worry, that discord.js package looks like its missing its own module anyway

sick birch
#

oh its by one of those youtube discord bot tutorial people

limber jolt
#

I removed discord.js and i still get error

mild token
limber jolt
mild token
limber jolt
#

@sick birch Its still not owrking 😭

#

working*

mild token
#
<@&1262112129818034268>

<a:f:1261728256348913725> 
Please click on the button below to get the sync time.

:alert: Note - You can only check sync of one league only.
2024-07-18 12:00:25 ERROR    discord.ext.tasks Unhandled exception in internal background task 'my_task'.
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\pypoetry\Cache\virtualenvs\afw-bot-0qM92z9o-py3.12\Lib\site-packages\discord\ext\tasks\__init__.py", line 241, in _loop
    await self.coro(*args, **kwargs)
  File "D:\AFW bot\afw_bot\ext\auto_sync_update.py", line 142, in my_task
    await message[0].delete()
  File "C:\Users\HP\AppData\Local\pypoetry\Cache\virtualenvs\afw-bot-0qM92z9o-py3.12\Lib\site-packages\discord\message.py", line 1001, in delete
    await self._state.http.delete_message(self.channel.id, self.id)
  File "C:\Users\HP\AppData\Local\pypoetry\Cache\virtualenvs\afw-bot-0qM92z9o-py3.12\Lib\site-packages\discord\http.py", line 754, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
await message[0].delete()

how this can print content but when calling .delete() it fails?

#

another thing i would like to ask how frequently message data get cached?

golden portal
#

wdym frequently? it gets cache as soon as on_message event gets fired

#

that message was probably deleted before you had the time to delete them, delete(delay=0) would put it in a task which suppress error btw

mild token
mild token
#

another thing i would like to ask i am trying to log deleted messages with on_message_delete how will i go for embed logging? like should i send full embed which got deleted?

golden portal
#

would just store the dict of that embed, embed.to_dict()

mild token
golden portal
#

nothin, you have to use audit log through guild.audit_logs

mild token
golden portal
#

nope, people would usually use audit logs inside on_message_delete

mild token
#

oh u mean audit logs is a method inside it?

golden portal
#

yea

#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the guild’s audit logs.

You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log) to do this.

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
mild token
#

oh i thought app audit log u r talking about

#

this thing tells who deleted the messages and how many it did?

mild token
golden portal
#

nop use on_bulk_message_delete

mild token
golden portal
#

oke

slate swan
#

how do u fix numpy not avalible

honest falcon
#
@bot.command()
async def create_thread(ctx):
    channel = ctx.channel
    thread = await channel.create_thread(name="My Thread", reason="Thread created by bot command")
    await ctx.send(f"Thread created: {thread.mention}")

when i use the command, the bot just create an "#unknow" thread, i think because it a private thread, how do i make it public?

fast osprey
#

!d discord.TextChannel.create_thread

unkempt canyonBOT
#

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

Creates a thread in this text channel.

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

New in version 2.0.
fast osprey
#

Either create it off a message or specify in the type parameter

craggy anvil
#

Why this happens:

#

Explanation:

  1. I click button
  2. It sends Confirmed because it was coded to send that, but button still loads like it wasnt clicked
  3. Shows error "This interaction failed"
#

Why does it show error if it did what i coded it to do

timber dragon
#

That means you aren't responding to the interaction

#

You should be using be interaction.response.send_message

slate swan
#

Hi I am just a newbie in python but I decided to make a project which will be verifying users and then giving them a role
Like when users join my server they can't message until they go to app link and verify I have seen this in many big servers and want to learn how it works

#

But I couldn't find it

fast osprey
#

This entirely depends on what exactly you're verifying about them

#

Verifying that they're a human? That they've read some rules? That they have the email they say they do? etc etc

slate swan
#

I once Manage to get email IDs but couldn't implement verify system

fast osprey
#

It is prohibitively difficult for you as an individual to verify if someone is a human. If you want to do this effectively, you will need to integrate with an interactive captcha service or the like

craggy anvil
#
import discord

class confirmview(discord.ui.View):
    def __init__(self, reset_callback, currency):
        super().__init__()
        self.reset_callback = reset_callback
        self.sender_confirmed = False
        self.receiver_confirmed = False
        self.sender = None
        self.receiver = None
        self.currency = currency

    @discord.ui.button(label="Correct", style=discord.ButtonStyle.success)
    async def correct(self, interaction: discord.Interaction, button: discord.ui.Button):
        if len(interaction.message.mentions) >= 2:
            if interaction.user == interaction.message.mentions[0]:
                self.sender_confirmed = True
                self.sender = interaction.user
            elif interaction.user == interaction.message.mentions[1]:
                self.receiver_confirmed = True
                self.receiver = interaction.user

        self.correct.disabled = True
        self.incorrect.disabled = True

        if self.sender_confirmed and self.receiver_confirmed:
            await self.confirmation_complete(interaction)
        else:
            embed = discord.Embed(description=f"{interaction.user.mention} has responded with 'Correct'", color=0x37f563)
            await interaction.response.send_message(embed=embed)

    @discord.ui.button(label="Incorrect", style=discord.ButtonStyle.secondary)
    async def incorrect(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.reset_callback(interaction)
        await interaction.message.delete()

    async def confirmation_complete(self, interaction: discord.Interaction):
        embed = interaction.message.embeds[0]
        embed.title = "Confirmed Role Identities"
        embed.description = "Both users have confirmed their roles within this deal."
        embed.set_field_at(0, name=f"Sending {self.currency}", value=self.sender.mention, inline=True)
        embed.set_field_at(1, name=f"Receiving {self.currency}", value=self.receiver.mention, inline=True)
        

        self.clear_items()

        await interaction.message.edit(embed=embed)


        deal_amount_embed = discord.Embed(title="Deal Amount", description="Please state the amount we are expected to receive in USD. (eg. 100.59)")
        await interaction.message.channel.send(embed=deal_amount_embed)
#

Why it doesnt work?

#

i mean i want it to edit embed, remove buttons from it and send deal amount (new) embed after both people clicked correct button

#

and if one person clicked correct button disable it for that person

craggy anvil
#

hewp uwu

golden portal
#

you need to describe what doesnt work about the code

craggy anvil
craggy anvil
#

i am not even sure if i coded it right

#

but it comes to this stage:

#

now it should remove buttons, edit that embed on top and send new one

golden portal
#

so in your confirmation_complete where you had self.clear_items(), just do await interaction.message.edit(embed=embed, view=self)
or better yet, just set the view to None that will do the same thing by removing the view from the message

limber jolt
#

PLEASE HELP MEEE. This stupid cog IS taking forever to load. Theres nothing wrong with It at all

pure glacier
quick gust
#

wait are you defining the class inside your command...?

fast osprey
#

The view class should be separate, and it internally should be declaring/adding whatever items it has

limber jolt
quick gust
#

yeah, read what solstice said

limber jolt
# fast osprey The view class should be separate, and it internally should be declaring/adding ...
from discord.ext import commands

# Create a bot instance with a command prefix
bot = commands.Bot(command_prefix='!')

# Dictionary to store log channels per server (guild)
log_channels = {}

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

    @commands.command()
    async def logchannel(self, ctx, channel_id: int):
        # Try to fetch the channel by ID
        channel = self.bot.get_channel(channel_id)
        if channel:
            # Store the log channel for the current guild
            log_channels[ctx.guild.id] = channel_id
            await ctx.send(f'Log channel has been set to {channel.mention}')
        else:
            await ctx.send('Invalid channel ID. Please provide a valid channel ID.')

    @commands.command()
    async def log(self, ctx):
        # Get the log channel for the current guild
        channel_id = log_channels.get(ctx.guild.id)
        if channel_id:
            channel = self.bot.get_channel(channel_id)
            if channel:
                await channel.send('A log has been created.')
            else:
                await ctx.send('Log channel not found.')
        else:
            await ctx.send('Log channel is not set. Use !logchannel <channel_id> to set it.')

async def setup(bot):
    await bot.add_cog(input(bot))```
fast osprey
#

What is leading you to believe this is taking time

limber jolt
slate swan
#

can some1 help fix RuntimeError: Numpy is not available

fast osprey
#

What exactly is taking a day, and how are you narrowing it down to it being caused by this code?

limber jolt
#

Failed to load cog: Extension 'cogs.input' has no 'setup' function.

fast osprey
#

And is the above the cogs.input module? That doesn't seem right

wild gate
#

@client.event
async def help(ctx):
await ctx.send("Here are the available commands\n")
how would I edit this cuz when I do !help in my server I get
​No Category:
check_channel
help Shows this message
shutdown_bot

Type !help command for more info on a command.
You can also type !help category for more info on a category.

fast osprey
#

The library has a default help command already, which is what you're seeing

wild gate
#

thanks

limber jolt
fast osprey
#

No I mean it clearly has a setup method

#

It would not cause the error you sent

limber jolt
fast osprey
#

Does the code you sent belong to a file called input.py that lives in a subfolder named cogs

fast osprey
#

You may need to import cogs.input and inspect the module, because it doesn't seem to be what you think it is

limber jolt
#

How od i inspect It?

#

Do*

fast osprey
#
import x
print(x.__file__)
print(x.setup)
limber jolt
# fast osprey ```py import x print(x.__file__) print(x.setup) ```

PS C:\Users\willi\Desktop\Free_Novem_discord_bot> & C:/Users/willi/AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users/willi/Desktop/Free_Novem_discord_bot/bot.py
Traceback (most recent call last):
File "c:\Users\willi\Desktop\Free_Novem_discord_bot\bot.py", line 33, in <module>
print(input.setup)
^^^^^^^^^^^
AttributeError: 'builtin_function_or_method' object has no attribute 'setup'
PS C:\Users\willi\Desktop\Free_Novem_discord_bot>

#

I imported It

fast osprey
#

input written literally is a built-in function

#

Try cogs.input?

limber jolt
# fast osprey Try `cogs.input`?

PS C:\Users\willi\Desktop\Free_Novem_discord_bot> & C:/Users/willi/AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users/willi/Desktop/Free_Novem_discord_bot/bot.py
Traceback (most recent call last):
File "c:\Users\willi\Desktop\Free_Novem_discord_bot\bot.py", line 33, in <module>
print(cogs.input.setup)
^^^^^^^^^^^^^^^^
AttributeError: module 'cogs.input' has no attribute 'setup'
PS C:\Users\willi\Desktop\Free_Novem_discord_bot>

fast osprey
#

And notice the file path there

#

It thinks that module lives in bot.py

limber jolt
#

wha-