#discord-bots

1 messages ยท Page 899 of 1

sick birch
#

Doesn't matter found out where the problem is

#
    @commands.Cog.listener()
    async def on_command_error(self,ctx,error):
        if isinstance(error,commands.MissingPermissions):
            await ctx.send("You can't do that")
            await ctx.message.delete()

right here

#

That's eating up all your errors

junior verge
#

What's wrong?

fallow mauve
#

no like when the bot prints smth in the console

sick birch
fallow mauve
#

but like how

#

ive never thought about this kinda thing before so idk where to start

sick birch
slate swan
junior verge
sick birch
sick birch
slate swan
sick birch
#

Or consider using cog only errors

hard trail
#

How do I make it delete the command message? I did ctx.delete() but keep getting this error

@bot.command()
async def verify(ctx):
  verified_role = get(ctx.guild.roles,name="Verified")
  guild = ctx.guild
  if ctx.channel.id == 945078080194621490:

    await ctx.author.add_roles(verified_role)
    embed1 = nextcord.Embed(title='Verified!', description = f"You have been verified successfully in {guild}!", color=nextcord.Color.green())
    await ctx.author.send(embed=embed1)
    await ctx.delete()
    return

  else:

    return
sick birch
#

on_command_error is global and it picks up every single error which sometimes can't be ideal (like now)

junior verge
fallow mauve
sick birch
sick birch
junior verge
#
@commands.Cog.listener()
    async def on_command_error(self,ctx,error):
        if isinstance(error,commands.MissingPermissions):
            await ctx.send("You can't do that")
            await ctx.message.delete()
            print(error)
``` Just like that
sick birch
#

Though it really feels like an XY problem to me

slate swan
#

!e on_print("s")

slate swan
sick birch
junior verge
#

Me?

sick birch
#

So it always runs, instead of conditionally

junior verge
sick birch
#

Alternatively

async def on_command_error(...):
  if isintance(...):
    # do something
  else:
    print(error) # very important
junior verge
#
@commands.Cog.listener()
    async def on_command_error(self,ctx,error):
        if isinstance(error,commands.MissingPermissions):
            await ctx.send("You can't do that")
            await ctx.message.delete()
        else:
            print(error)
sick birch
#

But printing the error won't really be all that descriptive, use the traceback library to print the entire traceback

junior verge
#

Uh okay, will this fix my problem though?

sick birch
#
import traceback

traceback.print_tb(error.__traceback__)
sick birch
junior verge
#

Hope so

sick birch
#

Give it a whirl and see what happens

junior verge
fallow mauve
junior verge
#

never defined error uh

sick birch
# fallow mauve yo no comprendo

I'm really thinking this is an XY problem. I'm assuming having an "on print" event is what you think is a solution to a different problem. What is the bigger problem you're trying to solve?

sick birch
junior verge
sick birch
#

Well from here on our you get all the errors and the problem is with other parts of your code

junior verge
#
@commands.Cog.listener()
    async def on_command_error(self,ctx,error):
        if isinstance(error,commands.MissingPermissions):
            await ctx.send("You can't do that")
            await ctx.message.delete()
        else:
            print(error)
``` How should I define error.
sick birch
#

You already have error provided to you in the error handler

fallow mauve
junior verge
sick birch
#

True, let's see

junior verge
#

That error is not defined in warn.py

fallow mauve
#

i gtg

sick birch
#

Knew that was an XY

fallow mauve
#

cool

sick birch
lyric tusk
#

how can i have image in a folder then use it in the main.py

sick birch
#

Looks like you chopped off the error

junior verge
sick birch
#

Hmmm

junior verge
#

Should I do OSError?

sick birch
#

No don't do that

junior verge
#

oki

sick birch
#

That's odd it should be defined

#

I guess remove the else and move print(error) to the function scope?

#

Maybe like

@commands.Cog.listener()
    async def on_command_error(self,ctx,error):
        if isinstance(error,commands.MissingPermissions):
            await ctx.send("You can't do that")
            await ctx.message.delete()
        print(error)
junior verge
#

ill try

#

Same error

sick birch
#

That is very strange indeed

vale wing
junior verge
#

oh

vale wing
#

You might have it somewhere else not in the error handler

sick birch
#

It can't be coming from anywhere else

junior verge
#

There is none somewhere else

vale wing
#

Ok

junior verge
#

I just did

sick birch
#

@junior verge instead of on_command_error try cog_command_error

flat solstice
#

so I'm not sure what's going on but my cog/group doesn't seem to be registering andI'm not getting any errors that would suggest there's a problem. I'm starting my bot like this to load the extensionspy async def start_bot(self): COG_PATH = pathlib.Path("../cogs/") for extension in COG_PATH.glob("*.py"): if extension.name != "__init__.py": print(extension) try: self.load_extension(extension) except Exception: print(f"Failed to load extension {extension}.", file=sys.stderr) print(traceback.print_exc()) await self.start(token)I then actually start the bot herepy loop = asyncio.get_event_loop() if __name__ == '__main__': loop.run_until_complete(client.start_bot())and this is the cog/group I'm trying to add```py
import discord
#from utils.helpers import userinfo
from typing import Union
from discord import Member, User, Interaction, Embed
from discord.app_commands import Group, command, describe

class User(Group):
def init(self, client):
self.bot = client

@command()
@describe(user="The discord user to get information for.")
async def info(self, interaction: Interaction, member: Union[Member, User] = None):
    await _userinfo_(interaction, member)

def setup(client):
client.add_cog(User(client))```

sick birch
#

It's not an event, just you have to override it

sick birch
#
class MyCog(commands.Cog):
  ...
  async def cog_command_error(self, ctx: commands.Context, error: CommandError):
    print(error)
#

You don't need the decorator just override it

outer wedge
#

yo guys, i am new to the python discord sever and python. Can you guys help me with a discord bot, i want to make one but i just dont know the ideas to

sick birch
vale wing
#

You should try this to see what args are provided to there

@commands.Cog.listener()
async def on_command_error(*args): 
    print(args)```
@junior verge
sick birch
#

that's a good idea

junior verge
#

lets see

flat solstice
junior verge
#

YE SYES YES

vale wing
junior verge
#

@sick birch Man I love you Love @vale wing as well absolute ๐Ÿ

vale wing
#

You fixed it?

#

Just interested what was wrong with it

junior verge
#

Yessss

junior verge
#

Now we got another error, it'll be just simple I guess

#
import discord, datetime, time
from discord.ext import commands


class Uptime(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(pass_context=True)
    async def uptime(self, ctx):
        start_time = time.time()
        current_time = time.time()
        difference = int(round(current_time - start_time))
        text = str(datetime.timedelta(seconds=difference))
        embed = discord.Embed(colour=ctx.message.author.top_role.colour)
        embed.add_field(name="Uptime", value=text)
        embed.set_footer(text="Daxbot.com")
        try:
            await self.client.send(embed=embed)
        except discord.HTTPException:
            await self.client.send("Current uptime: " + text)


def setup(client):
    client.add_cog(Uptime(client))
```  Uptime object has no attribute ctx
vale wing
#

pass_context deprecated

final iron
#

Someone actually following pep8 lemon_surprised

junior verge
final iron
vale wing
#

Remove that param at all

junior verge
#

alr

#

ty

vale wing
junior verge
#

I don't have a full error now anymore

#

Because of the error handller all shows is this

vale wing
#

And please show how is your client defined

vale wing
junior verge
vale wing
vale wing
junior verge
vale wing
#

But seems like client is bot

junior verge
junior verge
slate swan
#

then its await ctx.send?

vale wing
#

That's just in case

vale wing
junior verge
vale wing
#

Use ctx.send

junior verge
#

uh sure

vale wing
#

Not self.client.send

junior verge
#

yeah sorry

junior verge
#
import discord, datetime, time
from discord.ext import commands


class Uptime(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def uptime(self, ctx):
        start_time = time.time()
        current_time = time.time()
        difference = int(round(current_time - start_time))
        text = str(datetime.timedelta(seconds=difference))
        embed = discord.Embed(colour=ctx.message.author.top_role.colour)
        embed.add_field(name="Uptime", value=text)
        embed.set_footer(text="Daxbot.com")
        try:
            await ctx.send(embed=embed)
        except discord.HTTPException:
            await ctx.send("Current uptime: " + text)


def setup(client):
    client.add_cog(Uptime(client))
``` code btw
vale wing
#

Cause start_time and current_time are almost the same as you define them both inside of the command

junior verge
#

Which one should be outside?

glacial echo
#

ok i still cant figure this out

vale wing
#

You would want to make start_time a bot var

junior verge
#

erm, how?

#

just like that

vale wing
#
client = commands.Bot(...)
client.start_time = time.time()```
vale wing
# junior verge

This should work as well but it would reset after cog reload

#

I think

junior verge
#

Uh, lemme check

junior verge
#
import discord, datetime, time
from discord.ext import commands

start_time = time.time()

class Uptime(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def uptime(self, ctx):
        current_time = time.time()
        difference = int(round(current_time - start_time))
        text = str(datetime.timedelta(seconds=difference))
        embed = discord.Embed(colour=ctx.message.author.top_role.colour)
        embed.add_field(name="Uptime", value=text)
        embed.set_footer(text="Daxbot.com")
        try:
            await ctx.send(embed=embed)
        except discord.HTTPException:
            await ctx.send("Current uptime: " + text)


def setup(client):
    client.add_cog(Uptime(client))
``` How should I do it tho?
vale wing
#

Well personally I would use bot var as I said

vale wing
junior verge
#

uh Not like that I assume

#

like that

#

Still does not update @vale wing

vale wing
#

Why

junior verge
#

I don't know

vale wing
#

Could you show how you assigned it to your client

junior verge
#

wym

vale wing
#

Sry I gotta go maybe someone else will be able to help you cya

junior verge
#

Can anyone help me please

#
import discord, datetime, time
from discord.ext import commands



class Uptime(commands.Cog):
    def __init__(self, client):
        self.client = client
        client = commands.Bot()
        client.start_time = time.time()

    @commands.command()
    async def uptime(self, ctx):
        current_time = time.time()
        difference = int(round(current_time - self.client.start_time))
        text = str(datetime.timedelta(seconds=difference))
        embed = discord.Embed(colour=ctx.message.author.top_role.colour)
        embed.add_field(name="Uptime", value=text)
        embed.set_footer(text="Daxbot.com")
        try:
            await ctx.send(embed=embed)
        except discord.HTTPException:
            await ctx.send("Current uptime: " + text)


def setup(client):
    client.add_cog(Uptime(client))
``` My uptime command does not update
flat solstice
#

#bot-commands

#

i can never find the channel so i tagged it for myself

final iron
#

mixedCase shouldn't be used for variable names while snake_case should

#

I never left

flat solstice
junior verge
#
import discord
from discord.ext import commands

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

    @commands.Cog.listener()
    async def on_message(self, ctx, message):
            if self.client.user.mentioned_in(message):
                embed=discord.Embed(title="", url="https://www.linkpicture.com/q/daxbot.png", description="Hello, I am Daxbot! I am a discord bot created by ``Daxles#9999``", color=0x18c3fb), embed.set_author(name="Daxbot#0621", icon_url="https://www.linkpicture.com/q/daxbot.png")
                await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(Mention(bot))
``` Idea?
hushed galleon
#

on_message wont receive ctx

junior verge
#

oh

hushed galleon
#

dpy only passes in a message object, but since you specified two parameters it believes the message parameter is missing

junior verge
#

so what should I do

sick birch
#

Remove the ctx

hushed galleon
#

ya

junior verge
#

and then the ctx here?

hushed galleon
#

ctx.send is just a shortcut for writing message.channel.send

junior verge
#

So change it to that

hushed galleon
#

oui

junior verge
final iron
#

ctx.send is a shortcut for ctx.channel.send

junior verge
#

nvm

#

I am stupid

hushed galleon
#

obviously, but ctx is created from a message object so they essentially come from the same thing

final iron
#

Sure but again, it's not a shortcut

junior verge
#

Am I stupid or what

final iron
#

Send the code

junior verge
#
import discord
from discord.ext import commands

class Mention(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_message(self, message):
            if self.client.user.mentioned_in(message):
                embed=discord.Embed(title="", url="https://www.linkpicture.com/q/daxbot.png", description="Hello, I am Daxbot! I am a discord bot created by ``Daxles#9999``", color=0x18c3fb), embed.set_author(name="Daxbot#0621", icon_url="https://www.linkpicture.com/q/daxbot.png")
                await message.channel.send(embed=embed)

def setup(bot):
    bot.add_cog(Mention(bot))
hushed galleon
hushed galleon
#

^ you should either write embed.set_author on its own line, or chain the call by typing .set_author after the closing parenthesis: py embed = discord.Embed( title='is a good music player' ).set_author(name='foobar2000')

rocky hornet
#

is there a smart person that uses hikari?

hushed galleon
#

you're free to ask your question, someone will either know hikari or can read the docs and understand enough to help

vapid anchor
slate swan
#

smart advice from a smart person

compact crow
#

is there a reason when im putting someones avatar inside an embed it is very small, about the same size when you click on their account. am i doing something wrong?

compact crow
#

image

rocky trench
#

Can you attach a screenshot of the embed?

compact crow
#

using set_image
sure

#

teeny tiny

#

i tried adding it with add_field but it would always just be a url

#

and now its just small

#

you tried pip install discord.ui yeah

rocky hornet
compact crow
#

https://cdn.discordapp.com/avatars/{user.id}/{user.avatar}

rocky hornet
compact crow
#

me?

rocky hornet
#

yes

rocky hornet
#

i mean code that generates the url

compact crow
#

oh

rocky hornet
#

dont tell me that was it

compact crow
rocky hornet
compact crow
#

discordpy

rocky hornet
#

what version

rocky trench
#

Just use user.avatar.url

rocky hornet
rocky trench
rocky hornet
#

ok bro

rocky trench
#

I don't think ur comment was needed

rocky hornet
#

you are assuming: library they're using, version of that library

#

not helpful

rocky trench
#

Dpy 2.0 user.avatar.url
dpy: user.avatar_url

rocky trench
compact crow
#

my bad im back

rocky hornet
#

wdym of course ๐Ÿ’€

compact crow
rocky trench
rocky hornet
#

ur funny, the lib is dead

rocky trench
compact crow
#

one sec

rocky trench
rocky hornet
#

bro cant tell by the new slash implementation that its gonna be shit ๐Ÿ’€

rocky trench
rocky trench
rocky hornet
#

yea ok whatever, use dpy over disnake, nextcord and even hikari

#

API fkin v7 lmao

flat solstice
#

okay I have this app_commands.Group

import discord
#from utils.helpers import _userinfo_
from typing import Union
from discord import Member, User, Interaction, Embed, app_commands
from discord.app_commands import Group, command, describe

class User(app_commands.Group):
    def __init__(self, client):
        self.bot = client

    def _timestamps_(self, member, embed, avatar):
        embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True)
        if avatar == True:
            embed.add_field(name = "Avatar", value = f"[PNG]({member.avatar_url_as(static_format='png')})", inline = True)
        embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True)

    async def _userinfo_(interaction, member):
        member = interaction.user if member is None else member
        member_status = "No status" if member.activity is None else member.activity.name

        embed = Embed(title = f"{member}", description = f"Status: **{member.status}**\n*{member_status}*", colour = member.colour)
        embed.set_author(name = f"{member.id}", icon_url = member.avatar.url)
        embed.set_thumbnail(url = member.avatar.url)
        await _timestamps_(member, embed, True)
        if isinstance(member, discord.Member):
            roles = [f"{role.mention}" for role in member.roles]
            if len(roles) == 0: roles.append("No roles")
            has_key = [perm for perm in self.bot.config.key_perms if getattr(member.guild_permissions, perm)]
            if len(has_key) == 0: has_key.append('No permissions')
            embed.add_field(name = f"Roles: {len(roles)}",value = f"{len(roles)} roles" if len(" ".join(roles)) > 1000 else " ".join(roles), inline = False)
            embed.add_field(name =f'Key permissions', value = ", ".join(has_key).replace("_"," ").title(), inline = False)
        interaction.response.send_message(embed=embed)

    @app_commands.command()
    @app_commands.describe(user="The discord user to get information for.")
    async def info(self, interaction: Interaction, member: Union[Member, User] = None):
        await _userinfo_(interaction, member)```which is throwing an error of```py
Traceback (most recent call last):
  File "C:\Users\Teagan\Documents\Coding\Zupie\bot\main.py", line 4, in <module>
    from cogs.user import User
  File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\user.py", line 7, in <module>
    class User(Group):
  File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\user.py", line 36, in User
    async def info(self, interaction: Interaction, member: Union[Member, User] = None):
  File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 941, in decorator 
    return Command(
  File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 376, in __init__  
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 285, in _extract_parameters_from_callback
    _populate_descriptions(result, descriptions)
  File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 208, in _populate_descriptions
    raise TypeError(f'unknown parameter given: {first}')
arameters_from_callback
    _populate_descriptions(result, descriptions)
  File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 208, in _populate_descriptions
    raise TypeError(f'unknown parameter given: {first}')
TypeError: unknown parameter given: user```
left crater
compact crow
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.image.url: Scheme "6c9ff0d904002e1728a218e44247ea0b" is not supported. Scheme must be one of ('http', 'https').```
rocky hornet
#

i never said u cant

#

its just stupid

#

but whatever

#

@compact crow what version of the library

compact crow
flat solstice
left crater
#

1.7.3 uses v7 i think

rocky hornet
#

oh so he finally updated it

#

enjoy

left crater
#

thats what we have been trying to tell u

compact crow
#

im on 1.7.3

#

if im not mistaken

left crater
vast gale
#

ye 1.x is dead in april

rocky hornet
#

@compact crowhttps://discordpy.readthedocs.io/en/stable/api.html#discord.User.avatar_url

flat solstice
#

one of my bots is running 1.7.3 but the one of working on now uses 2.0

slim ibex
#

2.0 isnโ€™t stable

#

I wouldnโ€™t make a production bot with it

rocky hornet
#

2.0 isnt stable but yall love dpy so keep using it ๐Ÿ’€
dont even think about better forks

compact crow
#

what fork would you recommend other than dpy if i were to change

left crater
#

prob disnake

left crater
#

dpy has special place in our hearts

rocky hornet
#

@compact crow 3 possible reasons the image is small to you:

  1. avatar is small
  2. try pass image size to the url
  3. embed's max image size somehow doesnt satisfy you
flat solstice
#

none of the forks seem particularly good to me, i considered using hikari but that was such a drastic change and bc that's still in dev land those no decent into guides or tutorials

slim ibex
#

docs

#

you donโ€™t need tutorials. Read the docs

compact crow
rocky hornet
#

disnake is made by the creator of dislash, their 2.0 is stable for a very long time

compact crow
#

it was just me being a complete tool in the end

flat solstice
rocky hornet
#

nextcord afaik has support for sending audio packets to vc

#

its a new feature

slim ibex
left crater
#

what would be the best way to make a quiz bot?

#

im kinda lost

flat solstice
# slim ibex try pincer

The package is currently within the Alpha phase
that's the issue with most of them, they are all in dev land (not saying that's generally bad) and discord is just steamrolling ahead with new features faster than the libs can be updated or if they can catch up they seem rather tacked on (pycord)

slim ibex
#

who cares if itโ€™s in Alpha?

flat solstice
#

i don't massively, apart from if breaking changes get added

flat solstice
somber sky
#

what did i do wrong

slim ibex
#

you donโ€™t even tell us the error lmao

somber sky
#

there is no error it just doesnt do anything

flat solstice
#

is it a cog?

slim ibex
#

which part does nothing? Does it not send the first message or the second

somber sky
#

oh i had my console closed

slim ibex
#

ah yeah you donโ€™t pass ctx when invoking the command

somber sky
#

oh so just await message.edit?

slim ibex
#

thatโ€™s not what I mean

#

I said invoking the command

somber sky
#

what thhat mean

slim ibex
#

itโ€™s when you type the command in discord

#

What do you type?

slate swan
#

when doing bot.edit_guild(name=xyz, icon=icon) you need to set the icon as bytes, ive tried some stuff but that didnt work. does anyone know how to convert a png file/url into bytes used for the icon

somber sky
#

oops didnt mean to ping

uncut zephyr
#

Is it possible to make like a extra thread for each server my bot is on? So its like every Server has its own independent bot?

#

I am so lost with async and coroutine's

sick birch
edgy lion
#
             def check(m: discord.Message):  # m = discord.Message.
                            return m.author.id == interaction.user.id and m.channel.id == interaction.channel.id
                            # checking author and channel, you could add a line to check the content.
                            # and m.content == "xxx"
                            # the check won't become True until it detects (in the example case): xxx
                            # but that's not what we want here.

                        try:
                            #                        event = on_message without on_
                            msg = await self.bot.wait_for(event='message', check=check, timeout=60.0)
                            # msg = discord.Message
                        except asyncio.TimeoutError:
                            # at this point, the check didn't become True, let's handle it.
                            await interaction.edit_original_message(content=
                                                                    f"**{interaction.user}**, you didn't send any message that meets the check in this channel for 60 seconds..")
                            return
                        else:
                            # at this point, the check has become True and the wait_for has done its work, now we can do ours.
                            # we could also do things based on the message content here, like so
                            # if msg.content == "this is cool":
                            #    return await ctx.send("wait_for is indeed a cool method")

                            await interaction.edit_original_message(
                                content=f"**{interaction.user}**, you responded with {msg.content}")```
https://cdn.discordapp.com/attachments/381965515721146390/951988168406761513/unknown.png why is str.content none?
uncut zephyr
# slim ibex Why would you do that?

Because the Bot has to work like this to function correctly. And I asked questions before, I tried to understand async functions etc but I just dont get it. And if this is possible, this would be a very good way to achive my goals

uncut zephyr
alpine furnace
slim ibex
#

The bot runs once. That means you would have tons of bots running

alpine furnace
#

Your best option is to try harder to understand, because what youโ€™re trying to do is much more difficult than using the library as itโ€™s meant

slim ibex
#

^

candid escarp
#

I get this whenever on website when i run my bot
No WebSocket UPGRADE hdr: None
Can "Upgrade" only to "WebSocket". using discord.ext.ipc can someone help plz

uncut zephyr
slim ibex
#

It isnโ€™t a "problem".

#

plain and simple that you shouldnโ€™t run the same bot instance on multiple threads

#

That is extra complication that wonโ€™t do anything

uncut zephyr
# slim ibex It will literally do nothing to have a bot on a separate thread

Okay so maybe I dont mean Threads, then I am sorry.
I just want, that variables cant be changed across servers.

For example if I define a variable

Server1
num = 5

and on another Server
Server2
num = 10

Then both values should be saved, but I want to work with num = 5 on Server1 and with num = 10 on Server2. Like independent.

does that makes sense?

final iron
#

Use a database

#

Simple, quick, easy and asynchronous

slim ibex
#

yeah thatโ€™s a simple database

uncut zephyr
# final iron Use a database

Is there a database based on python? I tried sql and sqlalchemy, but I really dont like it.

currently I am saving everything in simple files

slim ibex
#

With a record for each specific guild, with specific config

slim ibex
#

You can use ORMs along with dbs to not have to write raw SQL

uncut zephyr
slim ibex
#

thatโ€™s not how a relational database works

final iron
uncut zephyr
manic wing
#

guys, opinion on having an arg in the event decorator which is raw and it means you get passed raw event data instead of whatever class

slim ibex
uncut zephyr
slim ibex
#

itโ€™s a table

manic wing
final iron
#

Are you making an API wrapper?

manic wing
#

yes

slim ibex
#

๐Ÿ—ฟ

final iron
#

Yea so, what API?

manic wing
#

discord api? tf

final iron
#

Could be useful I guess

uncut zephyr
slim ibex
#

Minecraft api

slim ibex
#

all you have to do is make a schema for your db, connect to your db, sync your db with the schema and use the prisma functions

#

Docs will tell you how to do it

uncut zephyr
#

Okay I think thats my main problem, I dont understand the difference or what I have to do in general. I have a wrong unterstanding

slim ibex
#

Just learn some sql

#

And worry about ORMs later

uncut zephyr
#

Thats not the problem, but I cant imagine that this would work. I just dont understand how

slim ibex
#

Itโ€™s a DATAbase

#

it literally stores data based on relationships

uncut zephyr
#

Okay can I give you an example?

slim ibex
#

and uniqueness

uncut zephyr
#

I have a game and it should be only possible to play one at a time.
So I have a boolean called "running". If True, you cant start a new game.
And I have a lot of data which I store in lists.

I understand that a database would be great for my lists. That I should safe everything in a real database. But I still have (for example) this single var. which should be independently on each Server. (Because if Server A plays a game, Server B dan still start one).

So do I give "running" an entry in one of my tables in dependency of the Server ID? And do this basiclly with every var. I use during a game...

#

So I dont use any python variables and only Database entry's?

slim ibex
#

you can use the var to make a query

uncut zephyr
#

Sorry I dont understand what you mean.

final iron
uncut zephyr
#

I think so, yes.

slim ibex
#

learn basic sql before doing database

final iron
#

Alright

#

I'll use sqlite3 as an example

slim ibex
#

ok

#

How do you select from a table in a database

final iron
#

You talking to me?

slim ibex
#

no

#

๐Ÿ—ฟ

uncut zephyr
#

use database-xy;
Select * from mytable where...;

slim ibex
#

donโ€™t think the useis needed if a database connection is established already

uncut zephyr
#

yeah true

#

sorry for blocking the channel. Maybe create a help channel?

final iron
#
# Pretend the connection has already been established
my_var = connection.cursor().execute("SELECT is_running FROM your_table_name;")
#

I think this is right anyway

#

snake_case?

uncut zephyr
#

okay

final iron
#

๐Ÿฅณ

#

!pypi ConfigParser

unkempt canyonBOT
final iron
#

Where is the trash can smh

final iron
uncut zephyr
uncut zephyr
final iron
#

You're just doing message.guild.id

#

You should be using placeholders

uncut zephyr
#

how do you check it

uncut zephyr
final iron
#

You would do

# Pretend the connection has already been established
my_var = connection.cursor().execute("SELECT is_running FROM your_table_name WHERE server = ?;", (message.guild.id, ))
#

Not 100% sure though

#

I've actually never used placeholders

#

I only learnt about sql injection after I quit making my discord bot

uncut zephyr
#

ahh yes, i tried it with

my_var = connection.cursor().execute("SELECT is_running FROM your_table_name WHERE server = " + str(message.guild.id)) //WRONG

and it worked

manic wing
manic wing
uncut zephyr
#

Ahh okay thank you. But except this, it would be correct?

final iron
#

Changed it

final iron
#

It's better practice

manic wing
#

n

final iron
#

Technically no but I would like to make it a habit

#

Always employ good practice, even if you don't need to

manic wing
#

looks bad but you do you

final iron
#

Doesn't matter to me ๐Ÿคทโ€โ™‚๏ธ

manic wing
#

you cant just pull 'good practice' out of your ass

final iron
#

I can

buoyant igloo
#

Guys what is the user mention argument in discord.py

uncut zephyr
#

that escalated quickly lol

final iron
#

Theres a difference between doing it in python and SQL

uncut zephyr
buoyant igloo
#

Argument

final iron
#

In python it's unpythonic, in sql, it's good practice

sick birch
manic wing
sick birch
buoyant igloo
#

ok thx

final iron
uncut zephyr
manic wing
#

i dont particularly care

final iron
#

Why are you so aggressive

manic wing
#

im not

final iron
#

You are

sick birch
#

Guys tone it down a notch

final iron
#

What did I do lmao

sick birch
#

You're gonna scare people off from asking for help

manic wing
#

apologies

sick birch
#

great let's move on then

uncut zephyr
final iron
#

Yeah, you would

uncut zephyr
final iron
#

Yeah, you would do num = fetching from database etc.

uncut zephyr
#

I have a lot of variables which I only have to use for a very short amount of time, I have to do a database entry for everything right?

final iron
#

Not everything

#

Only if you want to keep the data there if the bot restarts

uncut zephyr
#

No I dont. And also the "is_running" is reset to False after every restart. So does it mean I dont have to safe it in a db?

#

I thought I understand everything haha

final iron
#

When your bot restarts the database will not be affected unless you do it yourself

uncut zephyr
#

yes I know. And thats all good. But I want to know, what I have to do with my variables which are just there to do "short tasks"

final iron
final iron
uncut zephyr
#

Yeah I got this. But also in a DB then?

I try to by clear, lets say I have this

num = 0
for i in range(20+len(username)) #I know len(username) does not exists, but say it does for a moment
  num = num + 5
print(num)

And this gets called once in a while. So num does not need to be saved, but if someone else on another server starts a game, this "num" will be overwritten by him. So what to do?

edgy lion
#
             def check(m: discord.Message):  # m = discord.Message.
                            return m.author.id == interaction.user.id and m.channel.id == interaction.channel.id
                            # checking author and channel, you could add a line to check the content.
                            # and m.content == "xxx"
                            # the check won't become True until it detects (in the example case): xxx
                            # but that's not what we want here.

                        try:
                            #                        event = on_message without on_
                            msg = await self.bot.wait_for(event='message', check=check, timeout=60.0)
                            # msg = discord.Message
                        except asyncio.TimeoutError:
                            # at this point, the check didn't become True, let's handle it.
                            await interaction.edit_original_message(content=
                                                                    f"**{interaction.user}**, you didn't send any message that meets the check in this channel for 60 seconds..")
                            return
                        else:
                            # at this point, the check has become True and the wait_for has done its work, now we can do ours.
                            # we could also do things based on the message content here, like so
                            # if msg.content == "this is cool":
                            #    return await ctx.send("wait_for is indeed a cool method")

                            await interaction.edit_original_message(
                                content=f"**{interaction.user}**, you responded with {msg.content}")``` https://cdn.discordapp.com/attachments/381965515721146390/951988168406761513/unknown.png why is welcomeMessage.content none?
uncut zephyr
#

Does that makes sense?

final iron
hardy yoke
uncut zephyr
uncut zephyr
hardy yoke
#

if num is located inside a command function, that shouldn't be a concern due to how async works

final iron
#

It wont be overwritten

uncut zephyr
#

okay that makes sense. Let me clarify, a function is

def whatever():
  print("yeah")

#and also something like

async def whatever2():
  print("yeah")

#but on_message is of not a function?
#

but on_message should be a function too. So everything in my code is in a function. I am confused, give me a moment xD

edgy lion
uncut zephyr
#

I feel kinda stupid right now. But I dont have code outside a function lol

final iron
#

Then you'll have no issues with variables being overwritten

#

That's how async programming works

uncut zephyr
#

so in both my examples I wouldn't had any problems?

#

Thats weird because I have problems ๐Ÿ‘€
I will try something

pliant gulch
#

Then when running the code you increment dict[id] by 5

#

Instead of doing num = num + 5 you can also just do num += 5

manic wing
#

hey andy

pliant gulch
#

If you want num to be incremented by anyone in the server, yea you'd do that

#

Otherwise set the key as the author's ID to have user specific nums

uncut zephyr
pliant gulch
#

Yea, you'd be accessing the dict through the guild's ID preferably, so you won't be editing other guild's num

uncut zephyr
#

okay like num = [server_id, 5]

pliant gulch
#

!e ```py
mapping = {1: 0, 2: 0}
mapping[1] += 5
print(mapping[1], mapping[2])

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

5 0
uncut zephyr
#

Now I am again lost, pep8 just said, I dont have to care about it inside a function

pliant gulch
#

See here, the first guild, example here

#

It's under 1, and it has it's own num value

uncut zephyr
#

ahh yeah

pliant gulch
#

You access the value, increment

#

Since it's key-value specific you won't be incrementing other guilds

uncut zephyr
#

makes sense. thanks.

pliant gulch
#

๐Ÿ‘

uncut zephyr
#

I guess its not working for me because I use to much global variables... I guess my own fault

#

Btw @final iron Thank you very much for your time, I really appreciate it!

#

sorry for the ping lol

final iron
buoyant igloo
#

How would I store user input for later use in discord.py

flat solstice
#
Traceback (most recent call last):
  File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\client.py", line 384, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Teagan\Documents\Coding\Zupie\bot\main.py", line 50, in on_ready
    await bot.tree.sync(guild=discord.Object(id=default_guild))
  File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\tree.py", line 659, in sync
    data = await self._http.bulk_upsert_guild_commands(self.client.application_id, guild.id, payload=payload)
  File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\http.py", line 501, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```is this saying it can't make application commands? bc I have given the bot that scope
uncut zephyr
#

you can save it in a file if you want

buoyant igloo
#

Ok thx

uncut zephyr
#

or what do you mean?

supple thorn
buoyant igloo
#

Like ask for user input on something then store that into a dictionary value

uncut zephyr
#

for a long time?

buoyant igloo
#

Yes

supple thorn
#

You could use a database

uncut zephyr
#

like even if you kill your bot and restart it?

buoyant igloo
#

Na

#

Cuz I use replit and databases donโ€™t work on replit

uncut zephyr
#

Everyone is so obsessed with databases haha

left crater
#

you could use global

#

but db are better

uncut zephyr
buoyant igloo
left crater
buoyant igloo
left crater
supple thorn
#

It sounds like you want something 24/7

buoyant igloo
buoyant igloo
left crater
buoyant igloo
#

I could also do globals() prob, but it never worked for me

heavy folio
#

anyone knows of any fun facts api

uncut zephyr
left crater
buoyant igloo
heavy folio
#

never worked with reddit before

left crater
uncut zephyr
# buoyant igloo Ok thx ima search that up

if you use

client = commands.Bot(command_prefix="&", help_command=None)

"client" in this case, you just have to write

client.var = blabla

every time and its like a global var.

heavy folio
left crater
pliant gulch
#

It is indeed blocking

maiden fable
unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

uncut zephyr
#

yeah exactly and the same with "client."

maiden fable
#

Yes

buoyant igloo
uncut zephyr
#

yeah I think so. Now you can use "bot.var" everywhere in your code. And it just gets deleted if you restart the bot or do something like "bot.var =0"

buoyant igloo
#

Is the variable the same for every user?

#

I assume so

uncut zephyr
#

yes

buoyant igloo
#

g = 0 @bot.command() async def g(ctx): global g await ctx.send(โ€œWhatโ€) def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel g += 1 globals()[fโ€œbot.var{g}โ€] = [msg]
#would this make it different for every user?

alpine furnace
# unkempt canyon

I hope these attributes are immutable, or else thatโ€™d be cringe

buoyant igloo
#

@uncut zephyr

uncut zephyr
buoyant igloo
#

Is there a way to make it different for every person?

pliant gulch
#

Make your g a dict, then use key-value of user-id to values

flat solstice
#
# main.py
from cogs.users import user

async def add_commands():
  bot.tree.add_command(user(bot))

@bot.event
async def on_ready():
    print('------')
    print(
      f'Logged in as {bot.user} (ID: {bot.user.id})',
      f'Connected to {len(bot.guilds)} guilds',
      f'Running version {version}',
      f'Running {len(bot.shards)} shards',
      sep='\n'
    )
    await add_commands()
    await bot.tree.sync(guild=discord.Object(id=default_guild))
    print('Sucessfully synced applications commands')
    print('------')

# cogs.users.py
import discord
#from utils.helpers import _userinfo_
from typing import Union
from discord import Member, User, Interaction, Embed, app_commands

class user(app_commands.Group):
    def __init__(self, bot):
        super().__init__()
        self.bot = bot

    def _timestamps_(self, member, embed, avatar):
        if not isinstance(member, discord.Member):
            embed.add_field(name = "Joined Server:", value = f"<t:{int(member.joined_at.timestamp())}:R>", inline = True)
        if avatar == True:
            embed.add_field(name = "Avatar", value = f"[PNG]({member.avatar_url_as(static_format='png')})", inline = True)
        embed.add_field(name = "Joined Discord:", value = f"<t:{int(member.created_at.timestamp())}:R>", inline = True)

    async def _userinfo_(interaction, member):
        member = interaction.user if member is None else member
        member_status = "No status" if member.activity is None else member.activity.name

        embed = Embed(title = f"{member}", description = f"Status: **{member.status}**\n*{member_status}*", colour = member.colour)
        embed.set_author(name = f"{member.id}", icon_url = member.avatar.url)
        embed.set_thumbnail(url = member.avatar.url)
        await _timestamps_(member, embed, True)
        if isinstance(member, discord.Member):
            roles = [f"{role.mention}" for role in member.roles]
            if len(roles) == 0: roles.append("No roles")
            has_key = [perm for perm in self.bot.config.key_perms if getattr(member.guild_permissions, perm)]
            if len(has_key) == 0: has_key.append('No permissions')
            embed.add_field(name = f"Roles: {len(roles)}",value = f"{len(roles)} roles" if len(" ".join(roles)) > 1000 else " ".join(roles), inline = False)
            embed.add_field(name =f'Key permissions', value = ", ".join(has_key).replace("_"," ").title(), inline = False)
        interaction.response.send_message(embed=embed)

    @app_commands.command()
    @app_commands.describe(user="The discord user to get information for.")
    async def info(self, interaction: Interaction, user: Union[Member, User] = None):
        await _userinfo_(interaction, user)
```this users command (my only command so far) doesn't seem to be registering on the guild (and i have re-invited the bot twice to make sure it has the correct scopes)
pliant gulch
alpine furnace
#

Not at that point I mean, but instead of custom attributes

uncut zephyr
#

But tbh I have kind of the same problem with my code, so I am not sure haha

pliant gulch
#

Just seems like bad practice to use global here

#

At least, I am assuming you mean global, as you'd use it for module level attributes

buoyant igloo
uncut zephyr
#

bot.var works like a normal var

pliant gulch
#

That code would give an syntax error

uncut zephyr
maiden fable
maiden fable
alpine furnace
pliant gulch
maiden fable
#

The variable. He wanted to know if it was settable only once or...

pliant gulch
#

Ah

#

Well, you can pretty much override anything N times in python, unless it is a reserved keyword

#

Unless otherwise, if your object implements a property with no setter

maiden fable
#

Mhm

#

That's what I meant by subclassing Bot

tacit token
#

This code write only 1 member, why?

pliant gulch
#

Your bot should have member intents, otherwise you won't be able to see any members, other than your bot

tacit token
#

and i how to add intents?

pliant gulch
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

buoyant igloo
#

Ok I tested it and it gives me some kinda text idk how to explain

tacit token
#
RuntimeError: Event loop is closed```
tacit token
#
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000028A5CCCFE20>
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__  
    self.close()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close    
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 745, in call_soon    
    self._check_closed()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
final iron
#

Try reading the error

pliant gulch
# unkempt canyon

You got to go onto the developer dashboard as this guide tells you to do

tacit token
#

thanks

buoyant igloo
#

How do you change message id to the message

left crater
#

wdym

buoyant igloo
#

I donโ€™t know if thereโ€™s a way, but something like this

letโ€™s say that the message id of Joe is 1

how would I convert 1 to Joe

uncut zephyr
#

you mean to his name?

left crater
#

he wants to get the message content by using the id

buoyant igloo
#

Ye

uncut zephyr
#

But what content? You can use message.content

buoyant igloo
#

๐Ÿ˜ฎ

uncut zephyr
#

xD

buoyant igloo
#

Wait lemme try that

left crater
#

i thought u knew that lmao

buoyant igloo
#

Yo thx I can store user input now

vague grove
#

how can I make my discord bot change its own nickname in a specific serve?

#

server\

buoyant igloo
#

If statements

uncut zephyr
unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the memberโ€™s data.

Depending on the parameter passed, this requires different permissions listed below...
heavy folio
unkempt canyonBOT
vague grove
#

yes ty

heavy folio
#

oh god

#

await ctx.me.edit()

vague grove
#

never knew .me ever existed

buoyant igloo
#

!d await ctx.me.edit()

unkempt canyonBOT
maiden fable
unkempt canyonBOT
heavy folio
#

docs kinda messed up

#

oh it isnt actually

slate swan
#

why

small igloo
slate swan
#

๐Ÿฅฒ

small igloo
slate swan
#

ok

small igloo
#

:V

slate swan
#

can i send codes??

#
    bot.db = await asyncpg.create_pool(database="Prefix",user = "postgres", password = "mypass")
    print("Db added successfully")

bot.loop.create_task(create_db_pool())```
small igloo
slate swan
#

๐Ÿ˜’

hasty crest
#

Does anybody know any way of getting the About Me of a certain user? The official Discord.py doesn't support it yet. So, is there some kind of third-party library that may help?

slate swan
#

pro ppls

slate swan
hasty crest
#

That's a Windows issue

small igloo
slate swan
#

hmm

#

i need help

somber sky
#

"Message is a required argument that is missing"

#

wym

#

that is the code?

#

oh

slate swan
somber sky
#
@bot.command()
async def activity(ctx, message):

  await ctx.send("Activity Check\n @everyone")
  await message.delete()
  await ctx.message.add_reaction(Check)```
somber sky
#

wym

native wedge
#

how would i make an eval command?

slate swan
hasty crest
slate swan
#

;activity hello

#

like

somber sky
#

oh im sped

#

ye i see

#

i have a thing that defines it

slate swan
#

...

flat solstice
slate swan
#

use try and except

#

hmm

somber sky
#

im trying to make it where when i say s.activity it deletes my message and sends the await ctx.send("Activity Check\n @everyone") and reacts to his own message with โœ…

#

i got it but it doesnt delete nor does it react

#

it just sends

slate swan
#

or what??

somber sky
#

exactly*

slate swan
slate swan
# somber sky eactly
async def activity(ctx):

  msg = await ctx.send("Activity Check\n @everyone")
  await ctx.message.delete()
  await msg.add_reaction(':white_check_mark:')```
#

๐Ÿ‘

maiden fable
#

Sure

#

Bro what

slate swan
#

try
except Exception as e:
await ctx.send(f'{e}')

maiden fable
#

Bot broken

slate swan
#

so it send error

slate swan
vast fog
#

Can anyone explain the meaning of ctx in discord?

#

I read the docs but still a bit confusedโ€ฆ

slate swan
#

hmm

slate swan
vast fog
#

Can you specify further @slate swan

slate swan
flat solstice
slate swan
#
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        await ctx.send("**Invalid command. Try using** `help` **to figure out commands!**")
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('**Please pass in all requirements.**')
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("**You dont have all the requirements or permissions for using this command :angry:**")```
slate swan
#

lmao i don't get it

#

ok bro

#

well i am noob lmao

#

๐Ÿ˜…

flat solstice
#

Wait are you trying to get logs of every command ran (successful and unsuccessful)? Or just the unsuccessful ones

frigid pendant
#
@bot.command()
async def Ping(ctx):
  bans = await ctx.guild.bans()
  #print(bans)
  for i in ban:
    #print(i)
    print(i["User id"])

y this not wronking?

silent ermine
#

So i am trying to see if someone pings more than 5 times and this error pops up
i know that it needs to be the same datetimes but hwo do I know which datetimes to use?py TypeError: can't subtract offset-naive and offset-aware datetimes

Code:

@bot.event
async def on_message(message):
    def _check(m):
        return (m.author == message.author
                and len(m.mentions)
                and (datetime.utcnow()-m.created_at).seconds < 60)
        
    if not message.author.bot:
        if len(list(filter(lambda m: _check(m), bot.cached_messages))) >=3:
            await message.channel.send("Don't spam mention!!!")```
frigid pendant
#
@bot.command()
async def Ping(ctx):
  ban = await ctx.guild.bans()
  #print(bans)
  for i in ban:
    #print(i)
    print(i["User id"])

y this not working? i get this error:

    ret = await coro(*args, **kwargs)
  File "main.py", line 28, in Ping
    print(i["User id"])
TypeError: tuple indices must be integers or slices, not str

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

Traceback (most recent call last):
  File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: tuple indices must be integers or slices, not str
   
frigid pendant
#

i wanna pring the user id of the loop ban

flat solstice
#

Well you could make a on message event and check if the msg starts with a command (message.startswith(bot.command_prefix + command) or you could make a JSON file and I'm each command just write data to the JSON saying which command was used and when (which is contained in ctx)

silent ermine
frigid pendant
#

that works

#

but it prings out this

silent ermine
#

!eval

ban = ['a', 'b']
for i in ban:
  print(i)
frigid pendant
#

BanEntry(reason=None, user=<User id=217353461933670403 name='! EssaPrime' discriminator='0001' bot=False>)
BanEntry(reason=None, user=<User id=311909271904190466 name='Shut yo bubble gum dum dum' discriminator='6912' bot=False>)
BanEntry(reason=None, user=<User id=373518542122909706 name='Kuri' discriminator='1686' bot=False>)
BanEntry(reason=None, user=<User id=376652583202324481 name='TheTrain' discriminator='4373' bot=False>)
BanEntry(reason=None, user=<User id=451138906612564008 name='OfCommunity' discriminator='1502' bot=False>)
BanEntry(reason=None, user=<User id=591939896319672341 name='vmp' discriminator='8218' bot=False>)
BanEntry(reason=None, user=<User id=694595888420749442 name='Ex' discriminator='0512' bot=False>)
BanEntry(reason=None, user=<User id=714881781408727189 name='SUMER' discriminator='1188' bot=False>)
BanEntry(reason=None, user=<User id=714889517433356389 name='yoru' discriminator='7154' bot=False>)
BanEntry(reason=None, user=<User id=741544459103109170 name='valueof' discriminator='4777' bot=False>)
BanEntry(reason=None, user=<User id=747960344298651718 name='yldJoM6yOpMs0CWS2UyO' discriminator='8447' bot=False>)
BanEntry(reason=None, user=<User id=761325978831290419 name='Kiitty' discriminator='1544' bot=False>)

silent ermine
#

the user name?

frigid pendant
#

i just want to print out the user id's of the banned users

silent ermine
#

tell me what the response is

silent ermine
frigid pendant
#

it prints "None"

silent ermine
flat solstice
#

Well it's 4am for me so I'll probs bot be quick at responding.

Also if you go down the route of the second suggestion I gave you then consider writing a separate function for working with the JSON file, then execute the function within each command and pass in relevant params

frigid pendant
#

errors

#

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

Traceback (most recent call last):
  File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/WealthyFrequentOrigin/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: tuple index out of range
final iron
#

!e

my_tup = (1, 2, 3)
print(my_tup[3])
unkempt canyonBOT
#

@final iron :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | IndexError: tuple index out of range
pliant gulch
#

Why index the BanEntry

#

It's a namedtuple, a lot easier to use dotnotation to access the user

#

!d discord.BanEntry.user

unkempt canyonBOT
flat solstice
#

Is that the full traceback?

#

Oh that's always fun

silent ermine
#

So i am trying to see if someone pings more than 5 times and this error pops up
i know that it needs to be the same datetimes but hwo do I know which datetimes to use?py TypeError: can't subtract offset-naive and offset-aware datetimes

Code:

@bot.event
async def on_message(message):
    def _check(m):
        return (m.author == message.author
                and len(m.mentions)
                and (datetime.utcnow()-m.created_at).seconds < 60)
        
    if not message.author.bot:
        if len(list(filter(lambda m: _check(m), bot.cached_messages))) >=3:
            await message.channel.send("Don't spam mention!!!")```
#

the loop is closed

#

try indenting

#

so open then close after the check

maiden fable
#

ask_prefix() ?

#

U forgot to call the function?

#

Why not use a Command?

#

Well, seems like an on_message

#

why not use get_prefix?

#

!d discord.ext.commands.Bot.get_prefix

unkempt canyonBOT
#

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

Retrieves the prefix the bot is listening to with the message as a context.
slate swan
#
    bot.db = await asyncpg.create_pool(database="test",user = "postgres", password = "pass")
    print("Db added successfully")

bot.loop.create_task(create_db_pool())```
glacial echo
#
@client.listen()
async def on_message(message):
  if message.author != client.user:
    await message.channel.send(f"{message.content} sent by {message.author}")

the first message from the bot was running this code on repl.it
the second message from the bot was running this code on my laptop in VSC

Why?

slate swan
sick birch
glacial echo
#

and how do i get those?

sick birch
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

sick birch
#

you need

intents.message_content = True

and make sure it's turned on in the discord developer portal as well

#

Without those the content of a message is not made available to you

glacial echo
#

ok so whats weird is both my repl and my local VSC instance are running identical code

sick birch
#

๐Ÿค”

#

Well identical code in theory produces identical results

glacial echo
#

my thoughts exactly

#

like i literally copy pasted the code from VSC into repl before this test and it worked in the repl and not in vsc

sick birch
#

Unless discord is treating your replit's gateway connection differently for some reason

#

Can you post the full code in a pastebin if it's too long?

glacial echo
sick birch
#

Alrighty let me take a look

#

Also looks like part of your token might be leaked, might want to consider changing it just to be safe

glacial echo
#

i cut out a huge chunk of it

#

dw

sick birch
#

Hmm yeah quite odd

#

Can you try to run like the most basic bot with just an on message on both replit and vsc?

glacial echo
#

ye sure

sick birch
#
import discord
from discord.ext import commands

client = commands.Bot(...)

@client.listen()
async def on_message(message):
  if message.author != client.user:
    await message.channel.send(f"{message.content} sent by {message.author}")
 
client.run(token)

just that

glacial echo
#

top is on VSC
bottom is on Repl

sick birch
#

Same thing it seems?

glacial echo
#

yeah

#

but its weird cause it is receiving the event, and receiving the author, and the channel

#

but not the content?

sick birch
#

I mean only thing I can think of is replit gets the message_content intent but vsc doesn't

#

But I don't know why the gateway would treat it differently

glacial echo
#

are they possibly sent over different ports?

sick birch
#

No both are websocket connections

#

Do you have the bot running in both the replit and vsc simultaneously?

glacial echo
#

no i specifically stop one instance before running the other

#

actully lemme try that rq

#

bruh moment

#

and its aways the repl replying forst

sick birch
#

Curious indeed

supple thorn
sick birch
#

@glacial echo and you're 100% sure you have your message_content intents set up properly?

#

Can you show your code?

glacial echo
sick birch
#

I suppose, but it's worth giving it a shot

#

It doesn't take ()

#

Just

@client.event
...
#

Also make sure to process_commands()

#

What was the error before

#

Alright

#

And also you're aware on_message only provides you with message?

#

well what do you expect client.command to be

#

That's a decorator, so not sure why you're trying to add it to a string

#

Are you just trying to print something when someone runs a command?

glacial echo
#

does this look right? or is this the wrong section

sick birch
sick birch
#

How is the exe file going to send commands to the bot?

#

@glacial echo

#

I see

#

There's a better way to do this, let me check the docs since I don't remember

glacial echo
#

hmmm that was off

#

but uh then why would it wokr on the replit

#

still broke

sick birch
glacial echo
#

still no message.content

sick birch
glacial echo
#
from discord import Intents
import discord
from discord.ext import commands

token = "token"

client = commands.Bot(command_prefix="b|", case_insensitive = True)

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

@client.listen()
async def on_message(message):
  if message.author != client.user:
    await message.channel.send(f"{message.content} sent by {message.author}")

client.run(token)
sick birch
#

Some like this

bot = commands.Bot(...)

@bot.before_invoke
async def before_invoke(ctx: commands.Context):
  ...
sick birch
glacial echo
#

ah

sick birch
#

That's exactly what you want. It runs a function before a command is called

#

of course, call a print inside the before invoke hook

#

Understood

#

yeah that works

#

Just do a print inside of it, nothing special

#

That coro will get called before any function runs

boreal ravine
#

follow naming conventions prayadge

sick birch
#

Yes, if it gets called then it's a valid command

boreal ravine
#

why

sick birch
#

ctx.command

#

keep in mind it's a discord.ext.commands.Command object not a regular string

odd prawn
#

Well, if we're to take it literally, before_invoke means before your function is called.
So, this is a function that is called before your command's method is called.

#

Y'know, just to explain a bit more precisely what's going on.

sick birch
#

Yes, I'd like to include there's also a @bot.after_invoke if that helps you understand it more

#

awesome

glacial echo
#

this is so weird

sick birch
#

Congrats, you've utterly stumped me ๐Ÿ˜„

long whale
boreal ravine
sick birch
glacial echo
#

man finding bugs in discord.py is not how i wanted this school project to go

slate swan
long whale
#

So should I be starting with discord.py or use smth lik pycord or hikari?

sick birch
sick birch
long whale
#

I'm trying to get my first boy built so which one would be recommended?

sick birch
slate swan
#

b-boy....?

long whale
#

Bot*

slate swan
#

lmao

long whale
#

Lol

buoyant quail
#

xD

glacial echo
sick birch
#

Uh fantastic question

sick birch
#

@glacial echo did set up message intents, maybe not included in that link but we turned it on and had it in the code

#

At least I hope

glacial echo
#

yes i put intents in my code and triple checked i enabled them in my developer portal

sick birch
#

Might want to comment on it saying you didn't include it but yes you did include the intents and it's the same behaviour

glacial echo
#

what is master and why would that change between repl.it and VSC

sick birch
#

master the is dev branch

#

You should've included the fact that you did actually have message_content intent enabled in both your code and the dev portal

glacial echo
#

mhm didnt think about mentioning that

alpine furnace
sick birch
glacial echo
#

i did

#

welp guess i wont be working on refactoring and optimizing my bot

#

there goes possibly all potential work over the spring break on this

maiden fable
alpine furnace
#

You might have an orphan crisis on your hands then

maiden fable
#

Lmaoo

alpine furnace
glacial echo
#

b r u h m o m e n t

maiden fable
#

Not surprising

#

replit installs from pypi

clever pivot
#
    if message.author == bot.user:
        return
    for word in bs:
        if word in message.content:
            await message.delete()
            await message.channel.send(f'{message.author.mention} message has been deleted\n**Reason: **Discord Server Invite')```
in here i made anti-invite for discord servers, but how do i make it deactivate this thing in partner channel?
maiden fable
sick birch
#

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

clever pivot
maiden fable
#

@sick birch the honor's all yours

clever pivot
#

uh does it work if i do

if message.channel == channel_partner```
proven pendant
#

hi, so I was making this thing where my bot sends msg in a particular channel
but I wanna make it send the msg after like specific time....for example after each 15 mins or 1 hour
smtg like that~ is that possible?

maiden fable
#

!d discord.ext.tasks.Loop

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
sick birch
#

this ones on you

maiden fable
#

Please don't leave me lemon_pensive

gaunt ice
#

hmhm

proven pendant
sick birch
maiden fable
#

!d discord.ext.tasks.loop in case u need docs

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
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/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
sick birch
#

i'm gonna watch your performance and rate you

maiden fable
#

Starts acting as if I'm the nicest person ever

proven pendant
maiden fable
#

Is cool

vast gale
frigid pendant
#
@command_name.error
async def command_name_error(ctx, error):
  if isinstance(error, commands.CommandOnCooldown):
    em = discord.Embed(title=f"Slow it down bro!",description=f"Try again in {error.retry_after:.2f}s.", color=0x00ff00)
    await ctx.send(embed=em)

why does this give me this error?

Traceback (most recent call last):
  File "main.py", line 65, in <module>
    @command_name.error
NameError: name 'command_name' is not defined

i cant find a solution anywere

maiden fable
maiden fable
vast gale
#

@maiden fable me in disnake server

frigid pendant
#
@bot.command()
@commands.cooldown(1, 3, commands.BucketType.user)
async def delall(ctx):
  if ctx.author.id == 474677613886177281:
    Info = {"Cmd": "Delall", "User": ctx.author.id}
    LogCMD("Misc/CommandLogs.json", Info)
    embed=discord.Embed(title="DELETING ALL KEYS!", description="", color=0xff0000)
    await ctx.send(embed=embed)
    for i in db.keys():
      del db[i]
      print("Deleted Key: " + i + "")
#

this command

maiden fable
#

Do @delall.error

vast gale
#

actually i need to be careful since that would actually ban you

maiden fable
frigid pendant
#

\but i wanna add a slowmode to all my commands

maiden fable
#

Use on_command_error then

boreal ravine
frigid pendant
#

and if their command cooldown isnt over then it sends them this

#

a custom command cooldown i meant

#

so like this?

@Use on_command_error
async def command_name_error(ctx, error):
  if isinstance(error, commands.CommandOnCooldown):
    em = discord.Embed(title=f"Slow it down bro!",description=f"Try again in {error.retry_after:.2f}s.", color=0x00ff00)
    await ctx.send(embed=em)
#

@maiden fable

maiden fable
#

Ah

#

Then use on_command_error

#

Change the decorator to @bot.listen("on_command_error")

cold oyster
#

What do they want?

#

It's not like that Im sure

frigid pendant
#
@Use on_command_error
async def command_name_error(ctx, error):
  if isinstance(error, commands.CommandOnCooldown):
    em = discord.Embed(title=f"Slow it down bro!",description=f"Try again in {error.retry_after:.2f}s.", color=0x00ff00)
    await ctx.send(embed=em)

this get a invalid syntax error niw

maiden fable
#

Uhhhh?

maiden fable
cold oyster
#
@client.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.CommandOnCooldown):
    await ctx.reply("Wait homie")```
#

Now if that is cogs then Idk

sick birch
#

That will consume all of your errors

cold oyster
cold oyster
sick birch
#

Yes, and you won't get any errors

cold oyster
#

Hmm

sick birch
#

Had someone earlier today with the same problem

maiden fable
#

Robin here, I'm out. Peace โœŒ

cold oyster
#

So that is the reason my code doesn't wrk

sick birch
#

It could be

cold oyster
#

So can you tell me what do I do?

maiden fable
#
else:
    raise error
cold oyster
#

With the errors?

maiden fable
#

Add this at the end

cold oyster
#

Oh, Right

sick birch
#

In the top level of the function scope you can either reraise it like hunter said or print it using the traceback library

proven pendant
sick birch
#
import traceback

traceback.print_tb(error.__traceback__)
cold oyster
#

Here we go-

proven pendant
maiden fable
sick birch
#

I suppose

cold oyster
#

@sick birch Thank you so much, Finally got the error

#

I mean I really just use else: raise error

sick birch
#

Great. That makes 2 of the same problems today

cold oyster
#
@client.command()
@commands.has_role(950040612625842186)
async def add_money(ctx, user: discord.Member, amount=None):
    if amount == None:
        await ctx.reply("**__INVALID AMOUNT__**, Please use `ayo add_money [user] [amount]`")
        return
    else:
        await ctx.reply(f"Successfully added {amount} to {user.name}'s wallet")
        users = await get_bank_data()

        users[str(user.id)]["wallet"] += amount
        with open("mainbank.json",'w') as f:
            json.dump(users,f)

Error : ```ret = await coro(*args, **kwargs)
File "c:\Users\HP\OneDrive\Desktop\Discord bot\main.py", line 27, in add_money
users[str(user.id)]["wallet"] += amount
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

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

Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 415, in _run_event await coro(*args, **kwargs)
File "c:\Users\HP\OneDrive\Desktop\Discord bot\main.py", line 15, in on_command_error
raise error
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\bot.py", line 1055, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for +=: 'int' and 'str'```

sick birch
#

Says it right there, can't add a number and a string

#

int() the string to add a number to a number

sick birch
#

^

cold oyster
cold oyster
boreal ravine
cold oyster
cold oyster
sick birch
#

It's only a matter of time before you descent into "JSON hell I call it" where it's just massive lines of int(something[str(...)])

boreal ravine
#

he makes bad tutorials

boreal ravine
sick birch
alpine furnace
proven pendant
#

can a bot send a msg in a channel WITHOUT anyone using the cmd?

sick birch
#

But unfortunately people insist on following them

boreal ravine
alpine furnace
#

bot.get_channel, and then you can send it in that returned channel ofc

alpine furnace
boreal ravine
alpine furnace
#

For context, Iโ€™ve never watched discord bot video tutorials because those are cringe, so yeah

gaunt ice
proven pendant
gaunt ice
#

lucas kinda descent

boreal ravine
#

he's great and all but his economy tutorial uses JSON instead of a proper database

boreal ravine
gaunt ice
#

bruh

sick birch
gaunt ice
#

but its so clear and understandable for beginners

boreal ravine
alpine furnace
gaunt ice
#

he done 14 parts playlist

#

before this

boreal ravine
alpine furnace
sick birch
gaunt ice
#

kinda tru

gaunt ice
proven pendant
sick birch
gaunt ice
#

anyway i need help

boreal ravine
#

ask away