#discord-bots

1 messages Β· Page 1047 of 1

fading marlin
#

you're not using in any way the get_prefix function, you just have commands.when_mentioned_or(prefix) as your command prefix

slate swan
#

@fading marlin can you type for me?

fading marlin
#

no

slate swan
placid skiff
#

you just have to assign your command prefix to your function

slate swan
#

Hmm

clear plinth
#

I have a bot hosted on heroku (I know, not recommended), but it's a small project & has been fine for me, but it's been offline for a couple of hours & I'm trying to track down why, but not sure where to look.. Any suggestions?

wicked atlas
clear plinth
wicked atlas
visual yarrow
#

@slate swan Keep it server-appropriate please.

clear plinth
potent spear
#

we have to see some code ofc, just errors don't help us that much

upbeat vigil
#

hey, i use replit and the repl keeps turning off despite me having a keepAlive.py file setup

sick birch
#

Are you using replit for hosting?

solid rover
#

hello ! so, i get something wired when trying to read the embed of another bot using discordpy/nextcord.
i found a stack overflow post of someone who seems to have the same problem as me but there are no answers to it
https://stackoverflow.com/questions/67362140/how-do-i-properly-read-embedded-messages-on-discord

The following code, wich worked some weeks ago when i wrote it; now returns an empty list even if the message clearly contain embeds :

if message.author.id == 678211574183362571:
  message_content = message.embeds
  print(message_content)
sick birch
#

Do you have message intents enabled?

solid rover
#

yup

sick birch
#

Both in the dashboard and your code?

#

You have intents.message_content = True in the code?

solid rover
#

lemme check

solid rover
sick birch
#

Can I see the code?

solid rover
#
@commands.Cog.listener("on_message")
async def message_send(self, message):
  if message.author.id == 678211574183362571:
    message_content = message.embeds
    print(message_content)
sick birch
#

Not that, I mean the part where you're setting intents

solid rover
#

oh, sorry

upbeat vigil
solid rover
#
# Intents
intents = nextcord.Intents.default()
intents.guilds = True
intents.members = True
intents.message_content = True

bot = commands.Bot(
    command_prefix=prefix,
    intents=intents,
    strip_after_prefix=True,
    case_insensitive=True
)
upbeat vigil
#

but the repl turns off an the host shows that its online

sick birch
#

So, you're trying to run code 24/7 with replit?

upbeat vigil
#

yeah

sick birch
#

That explains it

#

Not really much you can do about it. Replit isn't a host, was never meant to be up for more than a few minutes. Even using something like uptime robot or keepalive it's going to go offline regularly

#

Replit is for running quick snippets of code to test if something works, not for hosting applications

upbeat vigil
#

I see, any reccomendations of what i should use?

sick birch
upbeat vigil
#

alright

junior verge
#

Replit is shit

clear plinth
#

Anyone familiar with heroku? I know it's not much better than replit, but it's been fine for my use case, but it's currently offline and I'm trying to diagnose why. I'm not out of hours, so that's ruled out. Haven't edited the bot and has run fine until today

slate swan
quaint forum
#

Anyone know why this prints an empty list? Myself and another person are under the WINNER role. It prints "submissions", "WINNER", "[]" in that same order

        channelID = client.get_channel(submissionChannelID)
        print(channelID)
        role = discord.utils.get(channelID.guild.roles, id=winnerRoleID)
        print(role)
        pastWinners = role.members
        print(pastWinners)```
The goal is to simply get all the members with a certain role
#

and before you mention get_role, what difference would that make in solving the problem?

potent spear
quaint forum
#

print just the id?

#

Im printing the role on the 4th line if thats what you mean

#

it prints "WINNER" which is the role

quaint forum
#

uh. okay

#

the line is in the code I posted

pliant gulch
quaint forum
#

I gave it administrator

pliant gulch
#

Permissions isn't the same thing as intents

#

You'll need to pass member intents to your client in order to see the members

quaint forum
#

what are 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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.

potent spear
quaint forum
#

Okay thanks

#

Okay well I enabled intents on the dev page

#

and added the code ```py
from discord import Intents
from discord.ext import commands

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

#

hold on I think I realize whats happening

#

Ok yeah I sort of got it but Im getting a long string of information

#

[<Member id=231489473782942624 name='Person' discriminator='3323' bot=False nick=None guild=<Guild id=938266082182037594 name='bot testing' shard_id=None chunked=True member_count=3>>, <Member id=317342921739206656 name='coolbeansdude' discriminator='4877' bot=False nick=None guild=<Guild id=938266082182037594 name='bot testing' shard_id=None chunked=True member_count=3>>]

#

Any way I can just get the users ID?

hearty stream
#

hi

west mango
#

Quick question about working with sqlite3 in python for discord, do I need to wrap my attributes in quotes when defining their variables in order to fix this? I understand using all text fields is not good practice but just trying to get an understanding first.
Table Create

class MemeSubmission(commands.Cog): #  declaring the listener cog for async events
#initialize cogs
    def __init__(self, bot):
        self.bot = bot
        self.bot = bot
        self.db = sqlite3.connect('memes.db')
        self.create_tables()

    
    def create_tables(self):
        cur = self.db.cursor()
        cur.execute('''
            CREATE TABLE IF NOT EXISTS memes(
                messageid text PRIMARY KEY,
                userid text NOT NULL,
                username text NOT NULL,
                timestamp text NOT NULL
                )
        ''')
        self.db.commit()

Insert Values



    embmsg = await msg.channel.send(embed=embed, file=file)
                await embmsg.create_thread(name=thread, auto_archive_duration = archive_time)
                
                messageid = embmsg.id
                userid = msg.author.id
                username = msg.author
                timestamp = msg.created_at
                cur = self.db.cursor()
                cur.execute("INSERT INTO memes (messageid, userid, username, timestamp) VALUES    (?,?,?,?)", (messageid, userid, username, timestamp))
                self.db.commit()
                
                await msg.delete()

I'm assuming its just the datatype of userid, so thats why im wondering if its best to declare as string.

ERROR:

Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/runner/memes20/venv/lib/python3.8/site-packages/discord/client.py", line 375, in _run_event
    await coro(*args, **kwargs)
  File "/home/runner/memes20/cogs/listeners.py", line 64, in user_message
    cur.execute("INSERT INTO memes (messageid, userid, username, timestamp) VALUES (?,?,?,?)", (messageid, userid, username, timestamp))
sqlite3.InterfaceError: Error binding parameter 2 - probably unsupported type.
ξΊ§```
hushed galleon
west mango
#

oh that makes sense

#

going to try it

#

and that was it, im dumb. makes total sense thankds

hushed galleon
#

also their username might change over time, so usually its easier to store just their user id

#

with that you can mention them with the format <@id> or get/fetch the user whenever you need their name

west mango
#

makes sense, thanks! done

#

god I hate sqlite syntax as someone who works with both postgres and mysql

potent spear
#

you might also want to check out an async wrapper of a database

#

note that you'll have to also initialize that attribute (self.db) asynchronously in a startup task or whatever

west mango
#

so im initializing in a cog class then inserting further down in an actual cog as part of a listener event


class MemeSubmission(commands.Cog): #  declaring the listener cog for async events
#initialize cogs
    def __init__(self, bot):
        self.bot = bot
        self.bot = bot
        self.db = sqlite3.connect('memes.db')
        self.create_tables()
def create_tables(self):
        cur = self.db.cursor()
        cur.execute('''
            CREATE TABLE IF NOT EXISTS memes(
                messageid text PRIMARY KEY,
                userid text NOT NULL,
                username text NOT NULL,
                timestamp text NOT NULL
                )
        ''')
        self.db.commit()
@commands.Cog.listener("on_message") 
    async def user_message(self, msg):
        gallery = 952973551948922949
        thread = (f'{msg.author.name}\'s Dank Meme')
        archive_time = 60
        if msg.author == self.bot.user: #bot doesnt listen for itself in user_message
            return
        if msg.channel.id == gallery:
            if not msg.attachments: 
                await msg.delete()
                return
            attachment = msg.attachments[0]
            if attachment.filename.endswith(".jpg") or attachment.filename.endswith(".jpeg") or attachment.filename.endswith(".png") or attachment.filename.endswith(".gif"):
                file = await msg.attachments[0].to_file()
                file.filename = 'image.png'
                embed=discord.Embed(description=msg.content)
                embed.set_image(url='attachment://image.png')                        
                embed.set_author(name=msg.author, url=msg.author.display_avatar, 
                icon_url=msg.author.display_avatar)
                embed.set_footer(text=msg.created_at)
                
                embmsg = await msg.channel.send(embed=embed, file=file)
                await embmsg.create_thread(name=thread, auto_archive_duration = archive_time)
                
                messageid = embmsg.id
                userid = msg.author.id
                username = msg.author.name
                timestamp = embmsg.created_at
                cur = self.db.cursor()
                cur.execute("INSERT INTO memes (messageid, userid, username, timestamp) VALUES    (?,?,?,?)", (messageid, userid, username, timestamp))
                self.db.commit()

In Main.py file:

intents = discord.Intents() #these are the discord intents and you MUST TURN THEM ON IN YOUR DISCORD APPLICATION
bot = commands.Bot(command_prefix = "?", case_insensitive = True, intents = intents.all())
bot.remove_command('help')

# BUTTON VARIABLES


@bot.event
async def on_ready():
  print('Logged in as {0.user}'.format(bot))



async def load_extentions():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')

async def main ():
    async with bot:
        await load_extentions()
        await bot.start(os.environ['botsecret'])
asyncio.run(main())

is this not a good way of handling it @potent spear?

#

ignore some of the comments in main, forgot to delete them from when I was sharing my code with someone earlier and have since redone a few things.

#

but my understanding is with this way of doing it I am initializing db whenever the listener cog itself initializes, so if I want to access the db outside of this cog, I may need to reinitialize, but I dont think its an issue unless im missing something obvious.

potent spear
west mango
#

woah didnt even notice the typo. whats scary is I think I copied and pasted that same code with the typo from another bot of mine and its running in a server right now and I havent noticed anything go wrong. wonder what issues its causing lol.

slate swan
west mango
potent spear
slate swan
potent spear
slate swan
#

should not effect code-wise though

potent spear
west mango
#

oh I imsspelled it twice lmao

#

good for me

slate swan
potent spear
heavy shard
#

@potent spear i like your stress reducer ^_^

potent spear
west mango
# potent spear then you can use a context manager around the bot context manager ```py async wi...

never actually used context manager 😬 not sure if im understanding. so instead of:

#this is in cogfile.py
class MemeSubmission(commands.Cog): #  declaring the listener cog for async events
#initialize cogs
    def __init__(self, bot):
        self.bot = bot
        self.db = sqlite3.connect('memes.db')
        self.create_tables()

    
    def create_tables(self):
        cur = self.db.cursor()
        cur.execute('''
            CREATE TABLE IF NOT EXISTS memes(
                messageid text PRIMARY KEY,
                userid text NOT NULL,
                username text NOT NULL,
                timestamp text NOT NULL
                )
        ''')
        self.db.commit()

it would be:

intents = discord.Intents() #these are the discord intents and you MUST TURN THEM ON IN YOUR DISCORD APPLICATION
bot = commands.Bot(command_prefix = "?", case_insensitive = True, intents = intents.all())
bot.remove_command('help')
#-----------------------------I put this here in main.py
async with sqlite3.connect('memes.db') as db:
    bot.create_tables()
    
    
    def create_tables():
        cur = bot.db.cursor()
        cur.execute('''
            CREATE TABLE IF NOT EXISTS memes(
                messageid text PRIMARY KEY,
                userid text NOT NULL,
                username text NOT NULL,
                timestamp text NOT NULL
                )
        ''')
        bot.db.commit()

is that right?

potent spear
west mango
potent spear
#

where do you even get ctx.server from? that's old asf

west mango
potent spear
west mango
#

ill give it a shot, thanks.

potent spear
#

you'll need to use await db.execute() etc too then

#

wdym you don't know? did you even write it yourself?

west mango
#

got it, Im not 100% sure if I understand how this will affect referencing DB in multiple cogs but im going to do my due diligence first and try to figure it out

potent spear
#

by googling on stackoverflow or what? you should use the official docs

slate swan
#

well then you got some wrong help, for getting the server using Context, you need to use Context.guild

#

.server is a thing which has been replaced with . guild long time ago iirc

flint isle
#

umm how can i get the output in ## hours: ## mins and ## seconds from

import time
start_time = datetime.now()
await ctx.send(f"{datetime.now() - start_time}")```
west mango
potent spear
slate swan
#

i doubt if timedelta s have a strf

potent spear
slate swan
#

Nope

winter meadow
#

Hi, it's possible call a command with another command using cogs?

For example a command that send a dm to a specific user and invoke another command that bans the user

slate swan
#

yep

potent spear
slate swan
#

you can use Bot.get_command("command name").invoke @winter meadow

potent spear
#

channel is a string, you obv can't do +1 on that

winter meadow
potent spear
#

and now in english

flint isle
#

what is this for? cause that looks kinda sus

slate swan
#

yea~

heavy shard
#

<t:1652658950:R>

slate swan
#

the timestamp integer for you would be int(bot.start_time.timestamp())

flint isle
#

umm there is no code to create the channel

#

and its guild.channel

flint isle
#

as a message in the channel

flint isle
potent spear
flint isle
potent spear
heavy shard
#

it's called usually "unix timestamp" or "epoch", this is how usually time and date is stored internally

potent spear
#

nope, ofc not

#

you're not reading the docs nor using all your args in your function

flint isle
#

idk where the decimal came from

potent spear
flint isle
potent spear
#

you're too new to try a library like this
learn basic python first

pliant gulch
unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
pliant gulch
#

Instead of doing all this manually, just use this util method

flint isle
pliant gulch
#

Okay?

flint isle
flint isle
#

instead of the count of the largest item in the timestamp

heavy shard
#

i don't think there is

modest plover
#

For example

#

so <t:integer:T>

heavy shard
#

i think he meant like "10 hours 3 minutes 24 seconds ago"

modest plover
#

Oh

#

Yeah I don't think so, no

flint isle
torn sail
#

@bot.command**()**

heavy shard
hollow edge
#

yo

#

my bot is timing out because of the 3 second timeout thing

#

I can't really get the response to be under 3 seconds

#

is there a way to "respond" outside of a reply?

flint isle
heavy shard
#

send f"{days}days {hours}h {minutes}m {seconds}s ago" ... or edit this anyhow you want to

west mango
flint isle
#

What is the doc for setting a bots status?

potent spear
potent spear
west mango
#

nvm then, was just asking because you knew the context

flint isle
#

ok and how do i create a task to update it every minute or so

potent spear
#

first learn how to make and start a task
then add that code to change a status inside

sacred gull
#
    @commands.is_owner()
    @commands.command()
    async def blacklist(self, ctx, guild: discord.Guild = None):
        if guild is None:
            await ctx.send('missing arguments')
        db = sqlite3.connect('astral.db')
        cursor = db.cursor()
        cursor.execute('SELECT guild_id FROM whitelist WHERE guild_id = ?', (guild.id,))
        data = cursor.fetchone()
        if not data:
            e = discord.Embed(
                description=f'{ctx.author.mention}: `{guild.name}` is not a **whitelisted** guild',
                color=0xf8a424
            )
            await ctx.send(embed=e)
        if data:
            cursor.execute('DELETE FROM whitelist WHERE guild_id = ?', (guild.id,))
            e = discord.Embed(
                description=f'{ctx.author.mention}: `{guild.name}` has been **blacklisted**',
                color=0xa8ec7c
            )
            await ctx.send(embed=e)
        db.commit()
        cursor.close()
        db.close()

This is not deleting what it needs to delete from the database. I'm doing this on my test bot where everything is setup correctly. On my main bot it does work.
Anyone an idea on why?
There are no errors

flint isle
#

what is the doc you reccomend for tasks?

potent spear
potent spear
sacred gull
#

I know it is, but for me this is easier to recognize if I need to change something

#

And it doesn't affect the code

potent spear
#

it's a redundant check

sacred gull
#

What do you mean

#

Isn't it the same as an else statement?

potent spear
#

you're checking twice

potent spear
#

use else...

sacred gull
#

if not data:
..
else:
?

potent spear
#

yup

sacred gull
#

alr

potent spear
#

also, you should only commit in the else statement, there's not even a db execution in the if

sacred gull
#

i am only commiting in the else statement?

#

It's checking if there is data in the column, if there isn't it'll send a certain message, if there is it'll delete it and then it'll commit and close

#

or you mean tab it one more time?

#

anyway, all of this doesn't help me with my actual problem

potent spear
#

just debug it, then all should be clear...

#

aka, you should know till where the code runs and what it does that you didn't expect it to
since just thinking "ah shit, it didn't delete, something is wrong" isn't sufficient

sacred gull
#

This is the exact code that I use for my main bot and I'm just changing embeds, basically giving it a nicer style of everything

#

and it works on my main bot, but not on my testing bot

potent spear
#

does the command even run?

sacred gull
#

yeah it does

#

hence why i'm confused on why it doesn't work

#

at least the deleting part

potent spear
sacred gull
#

And also using the debug tool from pycharm itself normally shows me what's going on

potent spear
#

show me

sacred gull
#

Even that didn't detect anything

potent spear
#

just where you tried to print etc

#

do you have any on_command_error event? or on_message event?

sacred gull
#

But I can make one just for the command real quick

potent spear
#

here's the fix:

sacred gull
potent spear
#

add
else: raise error to that event and the error will smile back at you

#

since you're only handling the errors you want, the other errors get hidden, you have to handle those too

sacred gull
#

this is currently my global error handler


    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        ignored = (commands.CommandNotFound, commands.UserInputError)
        if isinstance(error, ignored):
            return

        if isinstance(error, commands.CommandOnCooldown):
            m, s = divmod(error.retry_after, 60)
            h, m = divmod(m, 60)
            if int(h) == 0 and int(m) == 0:
                await ctx.send(
                    f' {ctx.author.mention}, you must wait **{int(s)}** seconds to use the **{ctx.invoked_with}** command!')
            elif int(h) == 0 and int(m) != 0:
                await ctx.send(
                    f' {ctx.author.mention}, you must wait **{int(m)} minutes** and **{int(s)} seconds** to use the **{ctx.invoked_with}** command!')
            else:
                await ctx.send(
                    f' {ctx.author.mention}, you must wait {int(h)} hours, {int(m)} minutes and {int(s)} seconds to use the **{ctx.invoked_with}** command!')
        elif isinstance(error, commands.MissingPermissions):
            missing = [perm.replace('_', ' ').replace('guild', 'server').title() for perm in error.missing_permissions]
            if len(missing) > 2:
                fmt = '{}, {}'.format(", ".join(missing[:-1]), missing[-1].lower())
            else:
                fmt = ' and '.join(missing)
            _message = '{}: **{}** requires the `{}` permissions'.format(ctx.author.mention, ctx.invoked_with,
                                                                         fmt.lower())
            e = discord.Embed(
                description=f'![warn](https://cdn.discordapp.com/emojis/973524594956853268.webp?size=128 "warn") {_message}',
                color=0xffd33c
            )
            await ctx.send(embed=e)
        raise error
potent spear
#

I don't see an else

sacred gull
#

right, sec

#

Even that doesn't give me anything

potent spear
#

comment out the whole error handler and try again

sacred gull
#
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 375, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\ego\Desktop\beta\cogs\aevents.py", line 17, in on_command_error
    raise error
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 1325, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 940, in invoke
    await self.prepare(ctx)
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 862, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 769, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 640, in transform
    return await run_converters(ctx, converter, argument, param)  # type: ignore
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\converter.py", line 1297, in run_converters
    return await _actual_conversion(ctx, converter, argument, param)
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\converter.py", line 1179, in _actual_conversion
    return await converter().convert(ctx, argument)  # type: ignore
  File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\converter.py", line 723, in convert
    raise GuildNotFound(argument)
discord.ext.commands.errors.GuildNotFound: Guild "924718798286761994" not found.

potent spear
#

there you go

sacred gull
#

Guild not found, even tho the guild is in the database

potent spear
#

probably a type difference

#

string vs int or whatever

sacred gull
#

hm

#

any way i can fix that?

potent spear
#

I hope you're storing the guildID as an integer in your db

sacred gull
#

I am

potent spear
sacred gull
#

alright

#

i'll get to it later, thank you for helping!

#

ah actually, i think i figured it out. it's because the bot isn't in the guild.

#

that's why it isn't blacklisting the guild from the bot

west mango
#

im having some trouble successfully writing to a DB file in a cog after making some changes to utilize a single DB connection in async sqlite throughout my bot. Im able to creates tables and write to them but Im getting a corruption issue:
This is in main

async def load_extentions():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')

async def main ():
    async with aiosqlite.connect('memes.db') as db: 
        async with bot:
            bot.db = db
            cur = await bot.db.cursor()
            await cur.execute('''
            CREATE TABLE IF NOT EXISTS memes(
            messageid text PRIMARY KEY,
            userid text NOT NULL,
            username text NOT NULL,
            timestamp text NOT NULL
            )
            ''')
            await bot.db.commit()    
            await load_extentions()
            await bot.start(os.environ['botsecret'])
asyncio.run(main())

This is in a cog class

    embmsg = await msg.channel.send(embed=embed, file=file)
                await embmsg.create_thread(name=thread, auto_archive_duration = archive_time)
                
                messageid = embmsg.id
                userid = msg.author.id
                username = msg.author.name
                timestamp = embmsg.created_at
                cur = await self.bot.db.cursor()
                await cur.execute("INSERT INTO memes (messageid, userid, username, timestamp) VALUES    (?,?,?,?)", (messageid, userid, username, timestamp))
                await self.bot.db.commit()

Im not getting any errors but my DB file is being corrupted on both table creation and on write (probably from the creation though). I figure I shouldn't be referencing the connection in the way that I am in the cog, but I dont know 100% if that's related.

slate swan
#

is bot.logout() still a thing?

#

if no what are some alternatives (ping/dm me)

sage otter
#

bot.close()

#

@slate swan

slate swan
#

ah ty, bot.logout seems to work maybe as well, il give both a try

sage otter
#

They both do the same thing.

slate swan
#

How can I specify embed color when doing discord.Embed.from_dict?

granite parcel
#

how to get all animated emoji ctx.guild has?

slate swan
#

can u explain im not sure what to do? i also have time to compare

#

Any way on how I can reset a member their nickname? So it'll just delete the nickname if they have one and it'll show their discord name instead

slate swan
#

thank you

#

!d
discord.Member.edit

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...
quaint forum
#

How exactly do I get just the discord ID from a user object?

quaint forum
#

wow okay thank you lol

slate swan
#

NP

west mango
supple thorn
#

Sounds like more like a database problem

west mango
#

yep, ill keep troubleshooting in the meantime, thanks

supple thorn
#

You did

slate swan
#

how can I replace the .webp to .png in the user.avatar_url ?

quaint forum
#

Another question, I can't find this anywhere online; how do I retrieve the amount of reactions of 1 specific reaction on a message?

#

Okay I found message.reactions

feral lichen
slate swan
#

I get this when I select an option
The embed is edited but the bot sends this

sick birch
#

Code?

feral lichen
#

or topic

slate swan
#

uh wait nvm

feral lichen
#

show code lol

slate swan
#
view = View()
  view.add_item(select)
  ctx = await ctx.send(embed=helpEmbed, view=view)
  async def my_callback1(interaction):
    if select.values[0] == "Fun Commands":
      await interaction.response.send_message(await ctx.edit(embed=e2))
    if select.values[0] == "Server Related Commands":
      await interaction.response.send_message(await ctx.edit(embed=e4))
    if select.values[0] == "Utility Commands":
      await interaction.response.send_message(await ctx.edit(embed=e5))
    if select.values[0] == "Moderation Commands":
      await interaction.response.send_message(await ctx.edit(embed=e3))
  select.callback = my_callback1
slate swan
#

yes

slate swan
#

and thats the reason you dont make your own help command and subclass the default help command

#

Nvm I’ll use ephemeral messages for embeds

#

Cuz it works with embeds

slate swan
#

nor does interaction accept a Message object

#

which edit returns

slate swan
#

yes

sick birch
#

Ah okay, well I don't believe that's the correct way to deal with select menus

slate swan
sick birch
hasty chasm
#

heroku disabled hosting for github code so does anyone know any free hosting services i could use for my bot

slate swan
#

heroku ClI

hasty chasm
#

is that different from Heroku?

#

because they had a security breach from github and stopped supporting all code from it like a month or 2 ago

slate swan
#

u can use Heroku Cli to upload ur code

#

its in heroku deployment

supple thorn
slate swan
supple thorn
heavy shard
#

get raspberry pi and self-host

slate swan
supple thorn
slate swan
#

?

hasty chasm
#

@heavy shard how hard is it to do that because i have one

heavy shard
#

hmmm depends on how well do you know linux

spring flax
#
            for member in member_mentions:
                if isinstance(member, disnake.Member):
                    if GLOBAL_CODM_ROLE not in member._roles:
                        count += 1
                        res.append(member.mention)
                        
                if not isinstance(member, disnake.Member):
                    unkwown_count += 1
                    unkwown_names.append(str(member))
                    
                    
            not_found = "\n".join(unkwown_names) if unkwown_count != 0 else ''  

I have this code and not_found seems to return a list of all disnake.Members basically everyone who was mentioned in the message why?

heavy shard
spring flax
#

it's supposed to return the empty string because all of them are in the server

spring flax
supple thorn
slate swan
supple thorn
#

Or did you actually intentionally mispell it

spring flax
spring flax
#

i thought about it, and just decided to use it

supple thorn
#

I'm starting to think that's intentional

slate swan
#

fair enough if you want to use it like if 1234563545 in member._roles

spring flax
# supple thorn You named it as unkwown_count

it is ```py
unkwown_count = 0
unkwown_names = []

    if message.channel.id == GIVEAWAY_CHANNEL_ID:
        for member in member_mentions:
            if isinstance(member, disnake.Member):
                if GLOBAL_CODM_ROLE not in member._roles:
                    count += 1
                    res.append(member.mention)
                    
            if not isinstance(member, disnake.Member):
                unkwown_count += 1
                unkwown_names.append(str(member))
                
                
        not_found = "\n".join(unkwown_names) if unkwown_count != 0 else ''  
supple thorn
spring flax
spring flax
paper sluice
#

πŸ‘‹

supple thorn
spring flax
#

no idea what you're saying

#

can you be a bit more specific please

supple thorn
#

Sarth help

slate swan
paper sluice
slate swan
#

or are they

slate swan
supple thorn
#

I'm asking why

spring flax
#

one second

#

okay so my bad i fixed it but that wasn't causing the error

spring flax
#

i mean message.mentions

slate swan
#

oh

#

and is the command used in a server?

spring flax
slate swan
#

can you try printing that list

#

and see if they are disnake.Member s or not

spring flax
#

which list exactly?

slate swan
#

your member.mentions list

spring flax
robust fulcrum
#
@client.command()
@commands.has_permissions(manage_messages = True)
async def channel(ctx,channel: discord.TextChannel,message):
    await channel.send(message)

How can we make that bot also send name of person who used this command . Pls tel

loud junco
spring flax
robust fulcrum
#

I want send author and message both

spring flax
#

i probably should just iterate through and print the disnake.Members

robust fulcrum
loud junco
robust fulcrum
cloud dawn
loud junco
#
await ctx.send(f'{ctx.author.name}, {message}')
robust fulcrum
#

Ok

loud junco
robust fulcrum
#

No

loud junco
#

i mean

#

its basic python =.= u dont need to learn discord.py to know this

cloud dawn
unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

heavy shard
#

i wouldn't travel by that plane 😐

robust fulcrum
#

@loud junco will it work if i do it like this

await channel.send(f'sent by-{ctx.author.name},message-{message}')
robust fulcrum
#

I think yes

loud junco
#

??

#

i mean tell what u are trying to output

#

sent by-HydroRICO1209,message-hello world

robust fulcrum
#

I mean that it send message-{message} and sent by-{author}

robust fulcrum
loud junco
steel void
#

hey guys I need some help.

I basically have a command that pulls a random image from reddit and display it in the channel. The issue is some websites images wont embed itself into discord.

So, how can I add a check if it's from certaindomain to not send the image and get another one from reddit?

robust fulcrum
loud junco
robust fulcrum
heavy shard
#

you need "hello all" <-- in quotes

fleet sand
#

How to make the additional_param optional? Like we can have it or leave it blank.

@bot.command(name = "test", help = "test")
async def test(ctx, param1, param2, additional_param):
    #something
robust fulcrum
heavy shard
robust fulcrum
#

Oh k

quick gust
#

yeah or u could just add a * operator before the message param or whatever it is named

heavy shard
#

then he's gonna need to parse the channel manually

quick gust
#

no? what do you mean

heavy shard
#

or will it work like that? dunno to be honest

quick gust
#
async def channel(ctx, channel: discord.TextChannel, *, message):```
robust fulcrum
#

How can we use user string like
dm(ctx, (userstring),message)
Pls tell how to

slate swan
robust fulcrum
#

Like we can %dm @robust fulcrum (message)

#

So what will be the string at the name

slate swan
#

like the person who wants to dm?

robust fulcrum
#

ye

slate swan
#

add the argument member: discord.Member

robust fulcrum
#

ok

#

Thank u

slate swan
#

Id use

async def dm(ctx, member: discord.Member,*, message):
   await member.send(f'**{ctx.author.name}** said: {message}')
placid skiff
#

it's better to have an error handler for this one, as it is a command the argument passed could not be a member

slate swan
#
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/features/python.py", line 151, in jsk_python
    send(await self.jsk_python_result_handling(ctx, result))
  File "/app/.heroku/python/lib/python3.9/site-packages/jishaku/features/python.py", line 101, in jsk_python_result_handling
    result = repr(result)
  File "/app/.heroku/python/lib/python3.9/site-packages/discord/scheduled_events.py", line 230, in __repr__
    f"<ScheduledEvent id={self.id} "
TypeError: __str__ returned non-string (type Object)
``` i'm getting this error with 
```py
ctx.guild.scheduled_events
#

pls ping me if you can help asap

cloud dawn
#

!pypi heroku

unkempt canyonBOT
cloud dawn
#

😠

slate swan
#

it's just hosted on heroku bruh and it has nothign to do with error

cloud dawn
#

Oh yeah other lib was hikari kinda confused.

slate swan
#

πŸ’€ alright

cloud dawn
#

Anyhow you have the intent on?

slate swan
#

which one tho? πŸ’€ didn't know that we need intent for schedule event

#

!d discord.Guild.scheduled_events

unkempt canyonBOT
#

property scheduled_events```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of the guild’s scheduled events.

New in version 2.0.
slate swan
#

it does return list when there is no event in server

slate swan
slate swan
cloud dawn
#

.default should cover the intent tough.

slate swan
#

i've default one alreaedy

cloud dawn
#

Yeah okay

cloud dawn
slate swan
#

that's all there is to it

cloud dawn
#

Hmm lemme ask in dpy

slate swan
#

for proof

placid skiff
#

Lol why sending the whole traceback as response of the command

slate swan
#

update your dpy bro @slate swan

placid skiff
#

btw show the full code block

unkempt canyonBOT
#

discord/scheduled_event.py line 163

return f'<GuildScheduledEvent id={self.id} name={self.name!r} guild_id={self.guild_id!r} creator={self.creator!r}>'```
slate swan
#

this is the repr of ScheduledEvent , your's seems different

#

it's py-cord 😐

slate swan
#

Oh fuck im out.

#

πŸ’€ lmfaoo

#

alright, taht's okay

cloud dawn
#

py-cord... most likely the issue lies there.

slate swan
#

^^^

cloud dawn
#

Since they just copy paste every new update of dpy without testing.

slate swan
#

πŸ€” tbh... i'm just not sure about danny.. i'm kinda afraid if he discontinue the project dpy again

#

like.. i do believe him..he's good, but still uk

#

kinda the reason why i'm not using dpy 😐

placid skiff
#

use disnake then D_D

cloud dawn
#

It's fairly easy to hop between libraries.

slate swan
#

😩 it is easy, but it's not easy to 're-write' your whole bot uk

#

like.. too much work .. lmfao

#

i got the fix yay

placid skiff
#

Not really since it is a fork D_D

slate swan
#

owo

slate swan
cloud dawn
#

Yeah going from pycord to dpy is the most easiest when comparing to disnake or nextcord.

slate swan
#

go to scheduled_events.py , __repr__ property, they are returning a tuple, use " ".join() on that tuple and you are fine @slate swan

slate swan
placid skiff
#

lol imagine modify a package to use it

#

What i'm complain about, i did it too D_D

slate swan
#

:>

#

imagine not digging into the source code and monkey patching it

placid skiff
#

i dig into the source code to verify or find some curiosity about the code

potent spear
#

You're just holding ctrl+c ready

cloud dawn
#

I've never really modified any package I'd just find another solution or code my own.

potent spear
#

that's just reinventing the wheel

cloud dawn
#

Wheel is like 20 lines anyways.

potent spear
#

and you want to make that 50? xd

placid skiff
cloud dawn
#

You can also just use inspect or subclass to overwrite functions.

pure crypt
#

how can i make that the bor create a channel in a specific kategorie

potent spear
#

then use .create_text_channel() on that object

spring flax
#

the create_text_channel has a category kwarg iirc

placid skiff
#

in fact it his a guild method

potent spear
#

yup, you can choose

spring flax
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

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

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

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission
to create the channel...
placid skiff
#

you was faster xD

potent spear
#

either you pass the object as a kwarg, or you just use the object and call the method on that

pure crypt
#

Have i put the name or the id in category=None?

potent spear
#

category (Optional[CategoryChannel]) – The category to place the newly created channel under. The permissions will be automatically synced to category if no overwrites are provided.

pure crypt
#

create_text_channel doesn't work

spring flax
#

why

pure crypt
#

i have made bot.create_text_channel but "bot" object has no atribute create_text_channel

spring flax
#

it's a method of discord.Guild, not commands.Bot

pure crypt
#

is guild.create_text_channel korrect?

potent spear
#

yup

pure crypt
#

now name guild is not definied

potent spear
#

that's logic ofc... in your case, it's ctx.guild

stray carbon
#

any way to get someone's server avatar?

slate swan
#

!d
discord.Guild.icon

unkempt canyonBOT
pure crypt
slate swan
pure crypt
#

i know what i do wrong

slate swan
#

so fix?

#

if u know

pure crypt
#

No i thougth i know. I don't make it in a command i made it in an om_messge event

#

ctx doesn't work

slate swan
#

what do u want

pure crypt
#

if the bot got an dm he create an channel

slate swan
#

u need to add the guild id

pure crypt
#

i did it to make that the bot send the message in a specifik channel

pure crypt
#

where?

#

sry i'm really dumb

slate swan
#

ok so u want like if user dm the bot bot makes channel only on a specific guild?

pure crypt
#

Yes

potent spear
#

in that case, he has to get the guild first

#

those are some logic steps

slate swan
#

yes

slate swan
pure crypt
#

i can't copy the id because i'm on mobile in the browser but i guess if i'm on my computer i can do it

#

huge thanks

potent spear
slate swan
#

@commands.dm_only()

pure crypt
potent spear
#

print all the guilds...

pure crypt
#

ok i try it

slate swan
#
@bot.command()
@commands.dm_only()
async def s(ctx):
    g = bot.get_channel(id) or await bot.fetch_channel(id)
    await g.send("hi")
#

something like that

#

add fetch if u want

pure crypt
#

thanks

potent spear
loud junco
#

my bot has been rate limited since 10 hours ago(at least)
and now its still rate limited :D

placid skiff
#

gg

loud junco
#

replit being replit

slate swan
#

oh

loud junco
#

LOL

slate swan
#

uwu_mf i hate replit tbh

#

i only use it when im on someone's pc/laptop

placid skiff
#

next time you will buy a vps for hosting your things D_D

dense swallow
#

how do i hide certain cogs in commands.HelpCommand?

slate swan
stray carbon
potent spear
#

not implemented yet, I'm not so sure

modest ivy
#

can someone give me a proper guide for discord bot

#

to make one bc im struggling

loud junco
loud junco
dense swallow
#

is there any way to await this? ```py
mapping = dict(filter(lambda x: x[0] and ctx.bot.cog_is_public(x[0]), mapping.items()))

modest ivy
#

im shit

loud junco
paper sluice
dense swallow
#

this line works with other forks

paper sluice
#

what is cog_is_public?

dense swallow
#

its a function

#

which i made

paper sluice
#

is it a coro?

dense swallow
#
    async def cog_is_public(self, cog: commands.Cog):
        return cog.__module__ in self.public_extensions
cloud dawn
#

Why not just make it a def.

dense swallow
#

and this is public_extensions: ```py
async def setup_hook(self):
self.public_extensions = await self.load_extensions("cogs")

paper sluice
#

are you running mapping in an aync function?

dense swallow
#

yes

paper sluice
#

then do ... and await ctx.bot...

#

acutally wait

dense swallow
#

both works

paper sluice
#

hmm u can do lambda x: x[0] and (await ctx.bot.cog_is_public(x[0]) for _ in '_')

cloud dawn
#

You do need to define the mapping inside an async env

dense swallow
# paper sluice hmm u can do `lambda x: x[0] and (await ctx.bot.cog_is_public(x[0]) for _ in '_'...
Traceback (most recent call last):

  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
    ret = await coro(*args, **kwargs)

  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\help.py", line 945, in command_callback
    return await self.send_bot_help(mapping)

  File "D:\Projects\PizzaHat\PizzaHat\cogs_hidden\help.py", line 86, in send_bot_help
    mapping = dict(filter(lambda x: x[0] and (await ctx.bot.cog_is_public(x[0]) for _ in '_')))

TypeError: filter expected 2 arguments, got 1


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


Traceback (most recent call last):

  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
    await ctx.command.invoke(ctx)

  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 990, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore

  File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
    raise CommandInvokeError(exc) from exc

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: filter expected 2 arguments, got 1
paper sluice
#

did u put mapping.items() as second arg?

dense swallow
#

uhh no

#

ok putting mapping.items() resolved the error, thanks

slate swan
#

stop using normal commands concepts on slash commands, they are 2 different things.

dense swallow
#

^

slate swan
#

you would have to get that interaction message first, and use .add_reaction on it
and the method to get message varies in all libraries.

dense swallow
#

oh same person lol nvm

slate swan
#

thats not how it works.

dense swallow
#

doesnt this work?

slate swan
#

as i said, the method to do that is different for all the libraries.

#

yeah that should work and its message not messag

#
interaction = await ctx.respond()
await interaction.message.add_reaction()
#

ok guys so i have a discord bot where it has a command to create a category for something what it does is make a txt file with the name of the category the user chooses
and the user can also use a generate command and what it does is:
get the second argument which is the category name
with open(categoryname + '.txt' and whatever read type depending on what i need)
however if they get ur user they can get text from any txt file in your pc what can i do ?

loud junco
paper sluice
#

!e

from asyncio import run
from typing import Callable, Iterable


async def coro(i):
    return i % 2

d = {1: 2, 3: 4, 2: 4, 4: 6}

async def afilter(function: Callable, iterable: Iterable):
    for i in iterable:
        if await function(i):
            yield i
        
async def main():
    a = afilter(coro, d)
    print([i async for i in a])


run(main())
unkempt canyonBOT
#

@paper sluice :white_check_mark: Your eval job has completed with return code 0.

[1, 3]
modest ivy
#

i cant find anything usefull

paper sluice
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

loud junco
cloud dawn
#

Not having friends

paper sluice
loud junco
#

np

cloud dawn
#

Preferably not having anything planned the next year.

#

Best way to learn.

modest ivy
#

panda you dutch?

cloud dawn
#

Yes.

modest ivy
#

ah

cloud dawn
#

Superior language imo

#

All languages failed.

modest ivy
#

lol

loud junco
supple thorn
#

So the zen of python applies to you

cloud dawn
#

I wrote zen

#

||i didnt dont kill me||

modest ivy
#

i will
jk

supple thorn
cloud dawn
#

dies

modest ivy
#

funeral

loud junco
modest ivy
#

survives the gulag

modest ivy
cloud dawn
modest ivy
#

and after that they eat and drink

loud junco
#

alright alright its getting ot now

cloud dawn
#

Hydro is pretty ot

loud junco
#

huh

cloud dawn
#

Not too many gifs staff aren't too fond of those.

modest ivy
#

okay

loud junco
#

deletes it

#

try to keep it text-only ||if you wanna live here any longer||

dense swallow
paper sluice
paper sluice
#

i just called the function and got nothing

loud junco
#

who is zalgo

modest ivy
loud junco
modest ivy
#

lmao

loud junco
cloud dawn
loud junco
#

oo

paper sluice
#

!e

from asyncio import run

async def coro(i):
    return i % 2

d = {1: 2, 3: 4, 2: 4, 4: 6}

# async def afilter(function: Callable, iterable: Iterable):
#     for i in iterable:
#         if await function(i):
#             yield i
        
async def main():
    a = filter(lambda x: (await coro(x) for _ in '_'), d)
    print([*a])


run(main())
unkempt canyonBOT
#

@paper sluice :white_check_mark: Your eval job has completed with return code 0.

001 | <string>:15: RuntimeWarning: coroutine 'coro' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
003 | [1, 3, 2, 4]
paper sluice
paper sluice
#

async filter

slate swan
#
async def create_role(ctx, *, name):
    guild = ctx.guild
    await guild.create_role(name=name)
    await ctx.send(f'Role `{name}` has been created')```
how can i make it give the role specific perms while creating it?
timber kindle
#

how do I concatenate a say command? I want it to say "Hello World" when I do ?say Hello World, but it's outputting "Hello" instead

slate swan
brazen raft
#

Or you can use asyncio.gather

timber kindle
#
@bot.event
async def on_member_join(ctx, server: discord.Guild, member: discord.Member):
  await ctx.send(f"Ealcome to the server {member.mention}")
  await member.send("Welcome to {server}")
  await member.add_roles(974273691737288774)```

Tried joining on my alt and nothing worked
slate swan
#

also on_member_join only passes you a discord.Member object

timber kindle
slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.

dense swallow
#

the new timeout feature in discord.py is member.edit(mute=..) right?

slate swan
#

!d discord.Member.timeout

unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the
given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to
use this...
slate swan
#

@dense swallow ^

dense swallow
#

then what is member.edit(mute)

#

maybe its mute in vc?

slate swan
#

"mute (bool) – Indicates if the member should be guild muted or un-muted."

#

yes, it's mute in VC

#

I want to make a daily reward for my currency system, BUT idk how i would check if the user has claimed it already at that day.

terse coyote
#

how to give role to all members?

loud junco
#

how do i make like
me: rpm changedata 123
rpm: what data would u like to change '123' to
me: 1993
rpm: changed value of '123' to 1993

timber kindle
#
async def on_member_join(member):
  await member.send(f"Welcome to **{member.guild.name}**")
  await member.add_roles(*974273691737288774)

Last thing (Probably) I need, Why isn't the add role thing working? I need this for other things too

timber kindle
#

I looked on the api reference site and it said to put that I think

terse coyote
#

how to give role to all members?

dense swallow
placid verge
loud junco
#

how do i make it ask question and take value

timber kindle
loud junco
#

how ping me?

potent spear
unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

potent spear
#

just look up wait_for in the docs

loud junco
potent spear
#

!d discord.Client.wait_for

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...
stray carbon
#

nvm got it

slate swan
#

ping

loud junco
slate swan
#

event?

slate swan
#

wait for "message"

#

or reaction

loud junco
#

oo

terse coyote
timber kindle
terse coyote
loud junco
#
@bot.command(name='hack')
async def hack(ctx, arg:str):
  try:
    userid = str(ctx.author.id)
    if userid != '757508305256972338':
      await ctx.send('**ACCESS DENIED**')
    else:
      wait_for('mesage', /, *, check=None, timeout=None)
```is this how u do it
cloud dawn
loud junco
#

LOL ok

terse coyote
dull terrace
#

Haven't had a single server add since my bot page went live yesterday froggy_chill

timber kindle
slate swan
terse coyote
slate swan
stray carbon
#

ty

loud junco
slate swan
stray carbon
#

oh

dull terrace
slate swan
#

!d nextcord.Message.edit

unkempt canyonBOT
#

await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=..., file=..., files=..., append_files=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.
dull terrace
#

My first one didn't take nearly that long

loud junco
stray carbon
#

File "c:\Users\Akai\Desktop\Sugari\cogs\utility.py", line 33, in callback
await interaction.followup.edit(content=f'```diff\n{mymessage}\n```')
TypeError: edit() got an unexpected keyword argument 'content'

#

ig followup doesnt take edit()?

#

or wot?

forest ibex
#

guys
I want to make a bot that reacts to old messages
Can anyone help?

forest ibex
cloud dawn
placid skiff
#

What package are you using?

stray carbon
#

nextcord

#

it was edit_message

#

:Exit:

placid skiff
#

!d discord.on_raw_reaction_add

unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is
called regardless of the state of the internal message cache.

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
placid skiff
unkempt canyonBOT
#

await edit(*, reason=None, name=..., avatar=..., channel=None, prefer_auth=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits this Webhook.
placid skiff
#

this is the method that you are calling, you have to pass those args

stray carbon
#

me noob ikr

loud junco
#
@bot.command(name='check')
async def check(ctx, message, arg):
  return message.author == ctx.author and message.channel == ctx.channel
  message = await bot.wait_for("message", check=check) 
```what this does
robust fulcrum
#

Guys can anyone help me make a command
Called %pokedex {Pokemon}
Idk how to use APIs (https://pokeapi.co/)
Will anyone help me make this command pls πŸ™

potent spear
robust fulcrum
#

Ye

#

Not with api

potent spear
#

try to learn how to use an API first, then implement it in dpy
this isn't really dpy related

short silo
#

Ah, not related to this at all but are public threads only accessible to those who have access to the channels they were made in ?

Sorry for the unrelated question, but i can't test it myself right now..

robust fulcrum
#

There no video on APIs

potent spear
robust fulcrum
dusky pine
#
import requests

response = requests.get("https://pokeapi.co/something")
potent spear
#

it's like asking how to run before you can even walk

robust fulcrum
#

I want get Pokemon and it's gender from api

dusky pine
#

nevermind

#

@potent spear was right

#

Please read the PokeAPI docs, and learn how to use the requests module

slate swan
#

from the json response you get you would have to use data.get("name") for name, data.get("gender")

#

actually gender wont work*

robust fulcrum
slate swan
slate swan
#

just think about it, pokemons can be male or female , how are you supposed to get the gender of that'
its like Askin the "whats the gender of humans"

robust fulcrum
glad cradle
#

it's json

#

it's easy

robust fulcrum
#

I want to make a comamnd %pokedex (any Pokemon name here)

#

And it get me picture , gender , ability and it's location

glad cradle
#

ok

robust fulcrum
#

Will you help me?

glad cradle
#

that's not difficult

robust fulcrum
#

But me don't know how to

glad cradle
#

are you using replit?

robust fulcrum
#

So first what I have to do
import requests?

robust fulcrum
#

Me on mobile so i need to use it

glad cradle
robust fulcrum
#

Already bone

#

Done

#

Next @client.command
async def pokedex(ctx , pokemon)

robust fulcrum
heady sluice
glad cradle
heady sluice
quaint epoch
glad cradle
heady sluice
#

aiohttp PepeKing

quaint epoch
#

and await response.json()?

glad cradle
grim hare
torn sail
quaint epoch
slate swan
#

aiohttp is asynchronous

quaint epoch
slate swan
#

literally what i said

robust fulcrum
#

πŸ˜‚

grim hare
quaint epoch
slate swan
unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

quaint epoch
#

god why are my messages taking so long to send

robust fulcrum
#

My replit is lagging

#

Idk why

slate swan
slate swan
kindred epoch
robust fulcrum
#

@glad cradle what I have to do next?

slate swan
#

Sasukeeeee, so long

robust fulcrum
slate swan
robust fulcrum
#

Bruh

slate swan
#

nvm

kindred epoch
heady sluice
pure crypt
#

I have a question:
How can I make 2 different on_member_join events for 2 different servers? If I made them the bot sends both to both servers i tryed it with if guild_id == β€œId”: but It didn’t work

heady sluice
#

cope

robust fulcrum
pure crypt
heady sluice
glad cradle
robust fulcrum
robust fulcrum
glad cradle
heady sluice
#

aiohttp = betterrequests

robust fulcrum
#

But how to use it

#
@client.command()
async def pokedex(ctx , pokemon)
response = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon}")
data = json.load(response)
#

I made it like this

#

What's next to do

torn sail
#

Blocking section

robust fulcrum
#

Can anyone tell me steps to do it

torn sail
#

Here has a basic example

#

Oh wait I guess you can’t see it

robust fulcrum
#

I not understanding

robust fulcrum
glad cradle
#

read the docs

slate swan
maiden fable
#

But blocking

heady sluice
#

read again Ashley

maiden fable
#

That too

slate swan
maiden fable
#

...

slate swan
heady sluice
#

"no one ot'd me so Imma ot Hunter"

slate swan
#

I took that as a "request" not requests

#

πŸ˜”

maiden fable
robust fulcrum
#

Will anyone help me make the comamnd pls

maiden fable
#

What command

heady sluice
robust fulcrum
#
@client.command()
async def pokedex(ctx , pokemon)
response = requests.get(f"https://pokeapi.co/api/v2/pokemon/{pokemon}")
data = json.load(response)
#

This command

maiden fable
#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

heady sluice
#

a : is missing

robust fulcrum
#

Idk what to do next

slate swan
#

Yo someone wanna help me make a welcome bot?

heady sluice
#

mmmnooo....

maiden fable
#

!d discord.on_member_join @slate swan

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
robust fulcrum
heady sluice
#

only if you ask questions here about what you don't know how to do

slate swan
#

lmao

robust fulcrum
#

Hey will anyone help me make a %pokedex (any Pokemon name )
Command
Which will send me Pokemon image , gender , ability , location
With https://pokeapi.co/api/v2/pokemon api
Pls help make it
I will learn about it lator

slate swan
placid skiff
maiden fable
#

It can become annoying when that's not the answer to the question and the bot repeatedly sends that

placid skiff
#

There is a package that can check sentence similarity, with that it will be easy to not answer randomly

maiden fable
#

Ah, cool

heady sluice
#

yeah imagine the bot just tells a guy with an http error to restart the pc

placid skiff
#

Well i mean to answer to question like "How to send a message" and the bot will answer with the doc reference of the send method and will explain which object can use that method

#

something like that

heady sluice
#

and how does the bot know if it was a question

maiden fable
#

Looks a good feature tho

heady sluice
#

if someone is lazy writing

heady sluice
#

I didn't put a question mark now either

placid skiff
#

As i said there exist some packages which can check sentence similarity

maiden fable
#

Machine Learning and eating all the VPS's resources! πŸ‘€

sick birch
#

AWS has a ML service that can tell the tone of a sentence

maiden fable
#

(I would, at least)

sick birch
#

IIRC it’s AWS comprehend?

heady sluice
#

yes

sick birch
#

cool yeah, that’s what you’re looking for then

heady sluice
#

my internet's gone

placid skiff
#

there is even a package which checks sentence similarity based on the pronounce of words

#

there are a lot of possibilities

heady sluice
#

or do you see the same thing I do

sick birch
#

?

heady sluice
#

my internet's bamboozling me

#

do you see this too

sick birch
#

Yeah?

heady sluice
#

ok

#

my yes was an answer to hunter

#

then my internet went off

placid skiff
heady sluice
#

and I lost the context

unkempt canyonBOT
digital mason
#

How can I rename my bot help command to sth else ? Like !bothelp instead of !help

#

Because many bots are using !help too I dont want them to show up

supple thorn
sick birch
#

Not a command name issue

#

Either that or move to slash commands

digital mason
#

But the same will happen with slash commands if other bots have "help" as command right

supple thorn
#

Kek

digital mason
#

/help

quick gust
digital mason
#

Oh

#

What do I have to change in the code

#

Is it a lot

sick birch
sick birch
#

Multiple bots having same command name with slash commands is not a problem

#

Since the UI indicates which command belongs to which bot

digital mason
#

Do I have to install a package

sick birch
digital mason
#

commands.SlashCommand()?

sick birch
#

No

#

Check the documentation and examples

digital mason
#

Hate doc lol

sick birch
#

Well… being able to read documentation is important

digital mason
#

I only found slash command package

robust fulcrum
sick birch
robust fulcrum
#

Can anyone tell me steps to make a command %pokedex (Pokemon name)
Which sends me Pokemon picture , gender , ability , location
https://pokeapi.co/api/v2
With this api
Pls help

digital mason
#

I found nothing, only discord-py-slash-commands

robust fulcrum
scarlet aurora
robust fulcrum
sick birch
#

You don’t need to look for any packages

#

You don’t need to install anything, it works out of the box

sick birch
scarlet aurora
#

is blocking?

sick birch
#

Yes, requests is blocking

digital mason
#

Can you share a code snippet please

robust fulcrum
sick birch
scarlet aurora
sick birch
#

It blocks the event loop

#

You should never use requests in a discord bot

robust fulcrum
#

Ye

scarlet aurora
#

ok

sick birch
#

It’s very liable to crash your bot

robust fulcrum
#

Aiohtto

#

But idk how to use aiohtto

#

Cak anyone tell me steps to make a command %pokedex (Pokemon name)
Which sends me Pokemon picture , gender , ability , location
https://pokeapi.co/api/v2
With this api
Pls help

sick birch
#

That’s why documentation exists

robust fulcrum
#

Documentation very hard to understand

sick birch
#

Well, you need to learn how to read it

#

Read aiohttp docs first, then the pokeapi docs

robust fulcrum
#

I'll learn about it lator i just want to make command now

sick birch
#

Read the docs and it’s endpoints, params, etc

#

Otherwise it’s going to be difficult to make it

robust fulcrum
#

But if anyone tell me steps to make I'll be happy and learn about it after making command

quaint forum
#

I've been trying to count the reactions of one specific emoji on messages and I've been having some trouble.
I found message.reactions
Someone told me I had to get the object of the emoji now... how exactly do I do that?

heady sluice
#

is the reaction a custom emoji

quaint forum
#

No its a discord one ❀️

sick birch
heady sluice
#

if str(reaction.emojj) == "❀️"

robust fulcrum
gaunt mortar
#

Hi ! I recently started with discord.py and had to move on the v2 to use some features like text input and so on..
I was using cogs previously and had no problem with them before, when I moved to the v2 I had to change how cog were added and it's not working anymore :

How I proceed with v2:

extensions = ['modules.Bet', 'modules.CustomEvents']
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix="$", intents=intents, message_content=True, messages=True)


async def load_extensions():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            await client.load_extension(f"cogs.{filename[:-3]}")


async def main():
    async with client:
        await load_extensions()
        await client.start(BOT_TOKEN)


asyncio.run(main())

And then on each cog :

class Bet(commands.Cog):

    @commands.Cog.listener()
    async def on_ready(self):
        print("Test")

    @commands.command()
    async def bet(self, ctx):
        # myCode
        await ctx.send(embed=embed, components=[create, currentBets])


async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(Bet(bot))

The "on_ready" is working and printing "Test" on launch but commands are not working (no error, but nothing happens)
I spent some hours looking for a solution on this problem but found nothing helping me, any help would be appreciated..

sick birch
#

I don’t believe people can help you if you haven’t read the docs yourself and tried it first

sick birch
gaunt mortar
sick birch
#

Double check it