#discord-bots

1 messages · Page 81 of 1

muted valve
#

Hi i need some helo... id go to a help channle but this isnt reallt worthy of it... i have a bot i havent coded on for a few months its set to run all the time bjt theres 2 orher codes the codeer who ill call s foujd some code rhat logs messages well the file it dumps to we vant find where the code for it is... iv looked in all the files i can find on replit for tje bot. And the only other one wjo cpuld of done it is the 3rd codes H idk jow to find rhis code that logs it...
Is there anyway on replit i can see history of edited files and who edited them?

#

It wpuld help me solve this issue alot

sick birch
#

I don't believe so no, one reason to be using source control like Git

muted valve
#

Im veru inexperienced with codeing and so is S onlt H could do somthing like this

#

I canr find any file for the code rhat cuases the logging only where rje messages arw stored

#

Idk if theres hidden folders i canr access or what

#

I own tje bot and the replit page file thingu

#

I really would like some help im having a breakdown over this-
I did not want my bot to be used like rhis

edgy meadow
#
client = commands.Bot(command_prefix="?", intents=discord.Intents.default()) #put your own prefix here

@client.event
async def on_ready():
    print("bot online") #will print "bot online" in the console when the bot is online

@client.command()
async def ping(ctx):
    print("He did it!")
    await ctx.send("pong!") #simple command so that when you type "!ping" the bot will respond with "pong!"


why won't it work when i type ?ping ??? it just doesnt do anything

slate swan
#

i think the function name for both the buttons are same? which should be not

#

which should be not

edgy meadow
edgy meadow
torn sail
#

alright so there were some intents changes. define intents before intents = discord.Intents.default() and then intents.message_content = True then pass in that commands.Bot(..., intents=intents)

#

message_content also needs to be enabled in the dev portal

edgy meadow
#

aye that all worked!

#

that's pretty nice, thanks man!

light jungle
#

Hello everyone, I have a question how to make the bot answer you after you answered his message through the reply item (here is a screenshot, do not pay attention that it is in Russian).

torn sail
feral lichen
#

bot or user is missing something

sacred plume
#
[<Member id=942176793706790962 name='Mihai06' discriminator='5334' bot=False nick=None guild=<Guild id=985256066361225226 name='Neon Development' shard_id=0 chunked=True member_count=8>>, <Member id=975385095609405470 name='Neon Canary' discriminator='3883' bot=True nick=None guild=<Guild id=985256066361225226 name='Neon Development' shard_id=0 chunked=True member_count=8>>]

How can I get a list of only the member ids ? Like ```py
["942176793706790962", "975385095609405470"]

sick birch
#

Looks like you can't send a message to the ticket channel

unkempt canyonBOT
#

property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id "discord.User.id")
elfin moon
rare echo
#

a reply?

acoustic parcel
#

how do I get everyone on a list? when I type in this code, it only prints the bot.

async def on_message(message):
  for x in message.guild.members:
    print(x.name)```
sick birch
acoustic parcel
sick birch
#

!d discord.Intents.members

unkempt canyonBOT
#

Whether guild member related events are enabled.

This corresponds to the following events...

acoustic parcel
sick birch
#

Yeah default doesn't include member intents

#
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
acoustic parcel
#

alr ill give that a try ty

elfin moon
acoustic parcel
#

now it gives an error to the line where i run the bot

sick birch
#

Read that last chunk

#

It tells you everything you need to know

elfin moon
#

nvm i got it

acoustic parcel
crimson plover
#

how would i reply a message by finding a certain word within the message so for instance "Xerp: !8ball" or "this is the !8ball command" if it contains !8ball i want it to reply... with the 8ball message...

@a2m.event
async def on_message(message):#, case_insensitive=True):
ComPrefix = "!"

if message.author == a2m.user:
    return
if message.author.guild_permissions.administrator: ----Just ignore this(i know it wont work with what im attempting to do)

    if ComPrefix + '8ball' in message.content:
    # if ComPrefix + 'happy birthday' in message.content.lower():                
        options = ["Yes", "No", "yes definitely", "it is decidedly so", "signs point to Yes", "it is certain", "without a doubt",
            "most likely", "outlook good", "outlook not so good", "as I see it Yes", "better not tell you now", "cannot predict now",
            "MY REPLY IS NO", "you may rely on it", "REPLY hazy try again", "ask again later", "concentrate and ask again",
            "don't count on it", "very doubtful", "my sources say no"]  # all options
        await message.channel.send("The magic 8-ball says %s" %random.choice(options).lower())
light jungle
#

how can I make it so that after a person responds to a bot message (via the answer function in discord), the bot sends another message to him (I asked before how to do this, I never received an answer)

#

i tried to implement it through the if construct, but if it turned out to be implemented, I would not ask it, so here

elfin moon
#

and then reply

crimson plover
#

yes

#

i also want it to detect the username if possible

#

but for general commands for all players id be happy wiht just the !8ball (the happy birthday is commented out)

rare echo
crimson plover
#

but yeah if it detected multiple words like !8bal shake, or !8ball shake violently (not like id use those commands but as an example)

#

yes because the messages are streaming from a chat in game that relays the message the discord(this is built into the game itself not part of my bot just using the same token)

#

so when messages stream from the game it will be like Bot: Xerp: in game chat talk here

#

so i was using on_message to listen to the in-game chat then relay a message if it finds the command from the in game chat so i can do commands with the bot from within the game

#

so if someone found some loot and wanted to flip a coin then user could to !flip and they flip a coin... but the discord it would print as "BotName: User: !flip"

#

so if User: wasnt there it would be fine.. so didnt know how to make it find the word then reply

#

Sorry im trying to explain the best I can

rare echo
crimson plover
#

it would never start with the command though... it would start with <usernamehere>: !8ball

wicked atlas
#

The * argument means that every argument after it is keyword-only, meaning you need to specify it like reason=.... The / means that every argument before it is positional only, the opposite of *, where you CANNOT specify it like until=....

rare echo
#

i mean if it’s going to be a consistent <username>:something you should still be able to separate everything to what you need

sick birch
#

Positional only

winged coral
#

await the coroutine

bold kernel
#

« stop » function is not awaited on my code ?

winged coral
#

In your if name main boilerplate, i'd assume

#

Although the error does tell you exactly

bold kernel
#

I was convinced the error was on the func

slate swan
#

help :DD

#

dont worry its a sniper for privnote not nitro 💀

bold kernel
#

Define this variable intents=discord.Intents.default() and pass on the commands.Bot args this : intents = intents

storm cairn
#

Hi, could someone help me out with this, I'm trying to host my bot on my rasp (kali)

slate swan
#
ModuleNotFoundError: No module named 'httpx'
PS C:\Users\dynam\Downloads\boost-bot-main>```
sick birch
#

Or you can ask here for free

#

Claim a help channel

lime trench
#

how can i check if my bot has admin prms in a server?

slate swan
#

is it possible to leave servers my bot is in

#

or make invites for me to join them with the discord id?

jagged adder
#

how would i go about sending a discord msg without ctx? i presume i would need guild/channel, but i honestly have never manually wired it all together. the reason i cant use ctx is that im using a tasks.loop to get the func to be called at a set time; its not being called by a msg being sent

hushed galleon
#

your bot instance would be how you'd retrieve the channel you want to send to

#

there's several ways to do it but id say these are the normal approaches, assuming you have a specific guild/channel ID:

  1. Client.get_channel(cid) to get a channel by id from cache (looks in all guilds)
  2. Client.get_guild(gid) + Guild.get_channel(gid) to get a channel from a guild by cache (constant time lookup)
  3. Client.get_partial_messageable(cid) to get a fake channel suitable for sending messages (no cache required)
#

for methods 1 and 2 you'd want to make sure your bot is ready before the loop starts, otherwise the bot wont have loaded all channels into the cache: py @my_function.before_loop async def before_my_function(): await bot.wait_until_ready()

jagged adder
hushed galleon
#

yeah Bot inherits the same get_channel method from Client

jagged adder
#

coz mine is returning none

#

even tho i copied the id direct from my server

hushed galleon
#

can you show the code related to your loop?

jagged adder
#

server that has the bot in it ofc

#
@tasks.loop(seconds=1)
async def call():
    channel = bot.get_channel(624577501590454274)
    print(channel)
    await channel.send('hello')
    epoch_num = 1662859900
    if str(epoch_num) in str(time.time()):
#

the print/hello parts r for testing

hushed galleon
jagged adder
#

ohh

hushed galleon
#

also a 1 second send loop is pretty fast

jagged adder
#

well, i need a way to read epoch; i spose i could take a couple digits off if idc bout it being specific

#

ive had loads of trouble getting an easy to use timer system, so i just went with this one

jagged adder
#

that worked! cheers

#

just added the wait for into the same func

#
@tasks.loop(seconds=1)
async def call():
    await bot.wait_until_ready()
    channel = bot.get_channel(624577501590454274)
    print(channel)
    await channel.send('hello')
velvet sierra
#

guys, i have a popular verified bot where it's in more than 5k servers, but i was off for sometime, and now none command work, even the $utc to check the UTC time, it don't give me any error on the terminal, someone know something that changed these 2 last years that i should know?

#

the utc command is just:

@bot.command()
async def utc(ctx):
    await ctx.send(f"> {str(dt.datetime.utcnow().time())[:8]} utc")

and dont work anymore

sick birch
#

None of your commands will work and you'll need to do a full rehaul to slash commands

#

Discord most certainly won't grant you message content intents for regular commands

velvet sierra
sick birch
#

On slash commands?

velvet sierra
#

ye

sick birch
#

Tutorials are bad, see the examples in the github repo

jagged adder
#

how do i ping a role? ie whats the correct syntax

vale wing
long tartan
#

does anyone know any good free alternatives to heroku for discord bot hosting

sick birch
#

Either it's good but costs money or it's free and low-quality

long tartan
#

my bank account is lower quality

green lagoon
#

`import discord
import os
import random
from dotenv import load_dotenv
load_dotenv()

client = discord.Bot()
token = os.getenv('TOKEN')

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

@client.event
async def on_message(message):
username = str(message.author).split("#")[0]
channel = str(message.channel.name)
user_message = str(message.content)

print(f'Message {user_message} by {username} on {channel}')

if message.author == client.user:
    return

if channel == "random":
    if user_message.lower() == "hello" or user_message.lower() == "hi":
        await message.channel.send(f'Hello {username}')
        return
    elif user_message.lower() == "bye":
        await message.channel.send(f'Bye {username}')
    elif user_message.lower() == "...":
        jokes = ["..."]
        await message.channel.send(random.choice(jokes))

client.run(token)`

#

I got this error when running the code I learned from youtube

#

How do I fix this?

sick birch
#

Also is this lucas's video?

green lagoon
sick birch
#

Looks like it

green lagoon
#

Free code camp and other

sick birch
#

It's terrible, to be honest

green lagoon
#

:D

vale wing
#

Why do yall even like watching code videos

green lagoon
#

I didnt learn python to this

sick birch
#

I'd suggest trying to learn it on your own using the documentation & examples instead

#

These tutorials are... not the best, to say the least

vale wing
#

Imho they take too long time to watch

sick birch
#

I also don't see the appeal of being told which keys to press

#

I'd rather problem solve and come up with ideas on my own

vale wing
#

Isn't it better to quickly read some tutorial article or guide

green lagoon
vale wing
#

104 what

green lagoon
#

Exercise

clear mango
#

How can I push the user another selection menu in interaction.response?

vale wing
#

Where is the # in this tuple

#

What do you want to get from it

#

!e py tup = (1234,) print(tup[0])
?

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

1234
slate swan
#

that wasn't even a channel related question

vale wing
#

That's 1 element tuple why can't you

rare echo
rare echo
slate swan
rare echo
#

appreciate ya

rare echo
vale wing
#

That's like "hey guys how do I make an AI chatbot, I wanna put it into a discord bot" this would be more #data-science-and-ml related question

sick birch
#

yeah I find that people tend to come here with any problem that they encounter while making a discord bot with the justification that their problem is "related to a discord bot"

rare echo
vale wing
sick birch
#

Though if a problem is quick and simple enough we'll just answer it and send them on their way

slate swan
rare echo
#

it was an autopilot question because i knew it was entry level simple

vale wing
#

Man you don't really need to make excuses, we are just giving an advice

slate swan
#

or more like it's a general issue, isn't directed towards anyone

limber bison
#

class MyHelp(commands.HelpCommand):
    async def send_bot_help(self, mapping):
        embed = discord.Embed(title="PLAYGROUND Bot Help")
        for cog, commands in mapping.items():
           command_signatures = [self.get_command_signature(c) for c in commands]
           if command_signatures:
                cog_name = getattr(cog, "qualified_name", "No Category")
                embed.add_field(name=cog_name, value="\n".join(command_signatures), inline=False)

        channel = self.get_destination()
        await channel.send(embed=embed)

client.help_command = MyHelp()```
how can i make this
perm restricted
only admins can use\
rare echo
vale wing
vale wing
#

Well it has add_check ig you can use it in init, not sure if you can decorate this class with @check, or you could put some condition to the function itself

#

!d discord.ext.commands.HelpCommand.add_check

unkempt canyonBOT
#

add_check(func, /)```
Adds a check to the help command.

New in version 1.4.

Changed in version 2.0: `func` parameter is now positional-only.

See also

The [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") decorator
limber bison
# vale wing Well it has `add_check` ig you can use it in init, not sure if you can decorate ...
class MyHelp(commands.HelpCommand):
    @commands.has_permissions(manage_messages=True)
    async def send_bot_help(self, mapping):
        embed = discord.Embed(title="PLAYGROUND Bot Help")
        for cog, commands in mapping.items():
           command_signatures = [self.get_command_signature(c) for c in commands]
           if command_signatures:
                cog_name = getattr(cog, "qualified_name", "No Category")
                embed.add_field(name=cog_name, value="\n".join(command_signatures), inline=False)

        channel = self.get_destination()
        await channel.send(embed=embed)

client.help_command = MyHelp()```
like this
clear mango
#

How to let discord bot call another command when certain condition(s) are met?

clear mango
#

if condition=true, call command...

limber bison
#

no idea sory

vale wing
# clear mango if condition=true, call command...

Depends on where the command is stored at, if it's just a function in the same cog or the same module, you can just call it like a normal function ie await command(ctx, arg1, arg2), if it's in another cog it's better to use invoke method of Command object

#

I forgor

#

!d discord.ext.commands.Command

unkempt canyonBOT
#

class discord.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.

These are not created manually, instead they are created via the decorator or functional interface.
vale wing
#

I clearly remember it has invoke method

#

Oh wait

vale wing
#

!d discord.ext.commands.Context.invoke

unkempt canyonBOT
#

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

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function...
vale wing
slate swan
#

use the embed.set_image method not set_thumbnail

#

> text

#

text

#

with a space

#

ok

pulsar solstice
#

What is the best module to make a simple economy system?

dull knot
#
       NewcomerEmbed = disnake.Embed(title="...",
                                      description="",
                                      colour=disnake.Colour.random(),
                                      url="Link Here")

       NewcomerEmbed.add_field(name="...",
                              value="""...""", 
                              inline=True)


       NewcomerEmbed.add_field(name="...", 
                               value="""...""",
                               inline=True)


       NewcomerEmbed.add_field(name="**...**",
                              value="""...""")

I'm doing the inline part correctly, right? I want the 1st two Fields to be inlined but when It sends, the inlined fields are not working. What am I doing wrong here?

#

Here is what the embed sends me. Wait. Let me edit the dots for more context lol. A tad confusing as is

#

Anyone here? lol. I just need t fix this single inline problem and I'll be good

#

Ah, nvm lol. It seems that Inline is set to True as default

ionic edge
#

whats wrong here??

#
    @starboard.command()
    @checks.not_blacklisted()
    async def set(self, context: Context, channel: discord.TextChannel) -> None:
        async with self.client.pool.acquire() as connection:
            async with connection.cursor() as cursor:
                await cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={context.guild.id}")
                channelData= await cursor.fetchone()
                if channelData:
                    channelData = channelData[0]
                    if channelData ==channel.id:
                        return await context.send("This channel is already the starboard channel.")
                    await cursor.execute(f"UPDATE starboard SET channel_id = {channel.id} WHERE guild_id = {context.guild.id}") 
                    await context.send(f"Starboard channel set to {channel.mention}")
                else:
                    await cursor.execute(f"INSERT INTO starboard (guild_id, channel_id , starLimit) VALUES ({context.guild.id}, {channel.id} , 5)")
                    await context.send(f"Starboard channel set to {channel.mention}")
            await cursor.close()
#

discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'set' raised an exception: AttributeError: 'Bot' object has no attribute 'pool'

pulsar solstice
#
async def give(ctx, member:discord.Member, amount):
        ...
    await open_account(ctx.author)```
#

how should I put a check that the "amount" is a integer or not

maiden fable
#

amount: int

paper sluice
ionic edge
#

how to establish a connection??

paper sluice
#

you didn't set an attribute in your bot called, pool... So, you can't use it, first do that

maiden fable
#

You probably missed copying a part of code from that YouTube tutorial you were watching

pulsar solstice
#

How to get a Random user from the list of participants in your server?

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
pulsar solstice
lone lichen
#

Nono

#

!d discord.Guild.members

unkempt canyonBOT
pulsar solstice
#

hmmmm

lone lichen
#

This returns a list of all members

#

So if u have a guild object

#

Just do random.choice(guild.members)

ionic edge
#
    @checks.not_blacklisted()
    async def set(self, context: Context, channel: discord.TextChannel) -> None:
        connection = sqlite3.connect("database/database.db")
        async with connection.cursor() as cursor:
            await cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={context.guild.id}")
            channelData= await cursor.fetchone()
            if channelData:
                channelData = channelData[0]
                if channelData ==channel.id:
                    return await context.send("This channel is already the starboard channel.")
                await cursor.execute(f"UPDATE starboard SET channel_id = {channel.id} WHERE guild_id = {context.guild.id}") 
                await context.send(f"Starboard channel set to {channel.mention}")
            else:
                await cursor.execute(f"INSERT INTO starboard (guild_id, channel_id , starLimit) VALUES ({context.guild.id}, {channel.id} , 5)")
                await context.send(f"Starboard channel set to {channel.mention}")
            await cursor.close()```
#

am new to sql

pulsar solstice
ionic edge
#

how may i connect and use it?

pulsar solstice
ionic edge
#

dfiscord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'set' raised an exception: AttributeError: __aenter__

lone lichen
flint goblet
#

Hi

lone lichen
#

Hi

flint goblet
#

How to get next msg in dc py

lone lichen
#

!d discord.ext.commands.Bot.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.

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

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

This function returns the **first event that meets the requirements**...
flint goblet
#

Ok and how to get it's content like if it's embed

lone lichen
#

message.content

#

Or message.embeds

#

Lemme just

flint goblet
#

Seperate event

lone lichen
#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

x != y Checks if two messages are not equal.

hash(x) Returns the message’s hash.
flint goblet
#

Okok thanks

green lagoon
#

@bot.command() async def test(ctx, arg): await ctx.send(arg)
The 'test' cmd does not exist How do I fix this?

pulsar solstice
#

did you forgot to save the python file?

loud junco
dull knot
loud junco
#

i know but if there is no name
the function name will be the name

pulsar solstice
dull knot
#

First i've heard of that

loud junco
#

ya

green lagoon
#

I got it thanks

#

Forgot :D

dull knot
#

lol. Anyways, I've also got a qustion of my own (Regarding channel perms)

#

If I enable the Use External Emoji/Stickers for @ everyone but I restrict it using X role, would the users with the X role be unable to use External Emojis/Stickers unless they have a higher role that has the Use External Emojis/Sticker perms?

#

My bot's emojis are suddenly messed up due to this problem so I'm tryna fix it without really making a mess out of my server's perms

pulsar solstice
#

oop I didn't ment to tag you

#

soory

#

how to arrange my json data in separate line????

vocal snow
#

how are you dumping it

#

you're getting Forbidden for sending a message from what i can see

#

I would recommend pasting the code and error instead of sending SS, it's easier to debug

shrewd apex
#

!d json.dump

unkempt canyonBOT
#

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).

If *skipkeys* is true (default: `False`), then dict keys that are not of a basic type ([`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`int`](https://docs.python.org/3/library/functions.html#int "int"), [`float`](https://docs.python.org/3/library/functions.html#float "float"), [`bool`](https://docs.python.org/3/library/functions.html#bool "bool"), `None`) will be skipped instead of raising a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").

The [`json`](https://docs.python.org/3/library/json.html#module-json "json: Encode and decode the JSON format.") module always produces [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") objects, not [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. Therefore, `fp.write()` must support [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") input.

If *ensure\_ascii* is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If *ensure\_ascii* is false, these characters will be output as-is.
pulsar solstice
slate swan
#

ok i just reopened the app all good

spark igloo
#
from discord.utils import get

@bot.command(pass_context=True)
async def purge_members(ctx):
    for member in ctx.message.server.members:
        if not get(member.roles, name='calls'):
          else not get(members.roles, name='notifications'):
            await bot.kick(member)```
tidal hawk
#

Not discord bot related xD

cobalt jacinth
tidal hawk
cobalt jacinth
#

idk

#

its my discord bot script

#

idk why i am getting error

#

bot not coming online

tidal hawk
#

send full script

radiant parrot
#
@client.event
async def on_message(message):
    channel_final = client.get_channel(942848242616516638)
    channel_final_mi = client.get_channel(640107632690200587)# channel to ping message if approved
    button1 = Button(label="Approve!",style=discord.ButtonStyle.green)
    button3 = Button(label="Disapprove - No Mute", style=discord.ButtonStyle.blurple)
    button2 = Button(label="Disapprove!",style=discord.ButtonStyle.red)
    view = View()
    view.add_item(button1)
    view.add_item(button3)
    view.add_item(button2)
    message_channel = message.channel.id
    user_id = message.author.id
    channel_sent_in = message.channel
    # Check if message has content

    if message.content is not None and message_channel == 1017792577740734536 or message_channel == 1018468004121542716: #channel its monitoring
        # Add message content to list
        msg_list.append(message.content)
        img_list.append(message.attachments)
        await message.delete()
        print(msg_list)
        comhelper = '<@&889878315089932328>'
        staff = '<@&810238562053914695>'
        admin = '<@&811310504471035935>'
        channel = client.get_channel(1017118446284177419) # channel where checked if post is good
        embed = discord.Embed(title=f'Message detected in #{channel_sent_in}', color = 10181046)
        embed.add_field(name='Message: ', value=f'{message.content}')
        embed.add_field(name='User: ', value=f'{message.author}')
        embed.set_footer(text=f'Provided by Donks#1048 • {current_time}')
        await channel.send(f"Here: {comhelper + staff + admin}")
        await channel.send(embed=embed, view=view)``` with this code here, how would i also foward and image if it is sent
digital charm
#

Error:

AttributeError: 'Intents' object has no attribute 'member'```
Code:
```intents = discord.Intents.default()
intents.member = True```
ionic edge
#

discord.app_commands.errors.CommandInvokeError: Command 'set' raised an exception: AttributeError: __aenter__

#
    @starboard.command()
    @checks.not_blacklisted()
    async def set(self, context: Context, channel: discord.TextChannel) -> None:
        async with self.client.db.cursor() as cursor:
            await cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={context.guild.id}")
            channelData= await cursor.fetchone()
            if channelData:
                channelData = channelData[0]
                if channelData ==channel.id:
                    return await context.send("This channel is already the starboard channel.")
                await cursor.execute(f"UPDATE starboard SET channel_id = {channel.id} WHERE guild_id = {context.guild.id}") 
                await context.send(f"Starboard channel set to {channel.mention}")
            else:
                await cursor.execute(f"INSERT INTO starboard (guild_id, channel_id , starLimit) VALUES ({context.guild.id}, {channel.id} , 5)")
                await context.send(f"Starboard channel set to {channel.mention}")
            await cursor.close()```
vocal snow
#

Check the docs when you get AttributeError since the valid attributes are listed there

digital charm
vocal snow
ionic edge
#
    return sqlite3.connect("database/database.db")
ionic edge
vocal snow
#

An sqlite3 cursor definitely doesn't have aenter

#

You should use some async library like aiosqlite

slate swan
#

I'm kinda brain dead or smth but, how do I get a list of all the components inside a view

paper sluice
#

!d discord.ui.View.children

unkempt canyonBOT
paper sluice
#

slow bot

radiant parrot
#

How do i copy images from channels?

#

As atm got message.content grabbing text, but cant grab images

paper sluice
#

!d discord.Message.attachments

unkempt canyonBOT
ionic edge
#

@paper sluiceRYuga

radiant parrot
slate swan
digital charm
#

main.py

from event import Event

intents = discord.Intents.default()
intents.members = True
prefix = ".a"
bot = commands.Bot(command_prefix=prefix, help_command=None, intents=intents)
token = "the token"

bot.add_cog(Event(bot))

@bot.event
async def on_ready():
    print("The Bot is Online")

bot.run(token)```
event.py:
```py
import random
import discord
from discord.ext import commands
import sqlite3
import asyncio
import aiosqlite


class Event(commands.Cog):

    def __init__(self,bot):
        self.bot = bot


    @commands.Cog.listener()
    async def setup_hook(self):
        db = sqlite3.connect("bal.sqlite")
        cursor = db.cursor()
        cursor.execute('''CREATE TABLE IF NOT EXISTS bal (
            user_id INTEGER, cash INTEGER, crystals INTEGER, weapon_shards INTEGER, enhancing_stones INTEGER, event_pearls INTEGER, merging_stones INTEGER, fusion_earring INTEGER
        )''')
        print("Bot is Online")

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return

        user = message.author
        db = sqlite3.connect("bal.sqlite")
        cb = db.cursor()
        cb.execute(f"SELECT user_id FROM bal WHERE user_id = {user.id}")
        result = cb.fetchone()
        if result is None:
            sql = ("INSERT INTO bal(user_id, cash, crystals, event_pearls, weapon_shards, fusion_earring, merging_stones, enhancing_stones) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
            val = (user.id, 0, 0, 0, 0, 0, 0, 0, 0)
            cb.execute(sql, val)

        db.commit()
        cb.close()
        db.close()```
Not adding the value, nor creating the table
radiant parrot
vocal snow
#

And use aiosqlite, not sqlite3

digital charm
digital charm
digital charm
digital charm
vocal snow
ionic edge
vocal snow
#

!pypi aiosqlite

unkempt canyonBOT
digital charm
slate swan
#

does anyone have link to that discord bot which was written in 1 line?

digital charm
slate swan
digital charm
slate swan
#

yes

digital charm
#

must have been hard af

slate swan
#

not really

digital charm
#

oh

slate swan
#
std = type("std", (object, ), {"cout": type("cout", (object, ), {"__lshift__": lambda self, other: print(other)})()})()
std.cout << "x"```
ionic edge
#

for discord aiosqlite is better than sqlite ???

vocal snow
# slate swan 404
(lambda run, *args: run(discord.Client(), *args))((lambda client, *args: [func(client) for func in args]),(lambda client: setattr(client, '__await', client.loop.create_task)),(lambda client: setattr(client, '__commands', {'ping': (lambda message: client.__await(message.channel.send('pong'))), 'whoami': (lambda message: client.__await(message.channel.send('You are %s' %(message.author)))), 'help': (lambda message: client.__await(message.channel.send('\n{0}'.format('\n'.join(name for name in client.__commands)))))})), (lambda c: [setattr(c, key, value) for key, value in {'on_ready': asyncio.coroutine((lambda: print('Logged in as\n%s\n%s\n------' %(c.user.name, c.user.id)))), 'on_connect': asyncio.coroutine(lambda: print('Connected!')), 'on_error': asyncio.coroutine(lambda ctx, error: c.__await(ctx.channel.send(error))), 'on_message': asyncio.coroutine((lambda m: ((c.__commands[m.content[2:]](m), c.on_message)[1] if m.content.startswith('!!') else c.on_message)))}.items()]), (lambda c: [print('Running...'), c.run(token)]))
paper sluice
slate swan
slate swan
#

neither work

#

😱

radiant parrot
#
    attachment = message.attachments[0].url
IndexError: list index out of range``` how to fix this error?
#

cause if the user sends text without image, bot break

naive briar
#

You can check if the message contains attachment(s) or not

radiant parrot
#

How to do that 🙂

naive briar
#

Simply using if statement, example:

if not message.attachments:
    return

Return if message has no attachments

radiant parrot
naive briar
radiant parrot
#
 if message.content is not None and not message.attachments and message_channel == 1017792577740734536 or message_channel == 1018468004121542716: #channel its monitoring
        # Add message content to list
        msg_list.append(message.content)
        attachment = message.attachments[0].url
        await message.delete()```
naive briar
# radiant parrot Yes

That error was raised because the index you're trying to get an element from doesn't exist

naive briar
#

Uh

radiant parrot
#

Would you like me to send code in whole? So easier to read over

#

What its doing

naive briar
#

First is the not message.attachments will be True if the message has no attachments

#

So remove the not from it

radiant parrot
#

Done 🙂

robust fulcrum
#

Guys i want to make a utilis library for discord.py
What type of library should i make?

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
naive briar
# naive briar !or

Basically, in your code, if the message_channel is 1018468004121542716, it'll bypass the other checks.

 if message.content is not None and not message.attachments and message_channel == 1017792577740734536 or message_channel == 1018468004121542716
radiant parrot
#

Ahhhh I see

rain monolith
#

I wrote a bot but it doesn't work in Discord. When could I have made a mistake?

#

doesn't online

naive briar
radiant parrot
naive briar
#

You can use the code above because I've already fixed it for you, but you can still separate it if it looks messy.

radiant parrot
#

Ahh thank you v much

radiant parrot
#
await message.delete()
        print(msg_list)
        comhelper = '<@&889878315089932328>'
        staff = '<@&810238562053914695>'
        admin = '<@&811310504471035935>'
        channel = client.get_channel(1017118446284177419) # channel where checked if post is good
        embed = discord.Embed(title=f'Message detected in #{channel_sent_in}', color = 10181046)
        embed.add_field(name='Message: ', value=f'{message.content}')
        embed.add_field(name='User: ', value=f'{message.author}')
        embed.set_image(url= attachment)
        embed.set_footer(text=f'Provided by Donks#1048 • {current_time}')
        await channel.send(f"Here: {comhelper + staff + admin}")
        await channel.send(embed=embed, view=view)```
slate swan
slate swan
radiant parrot
#

and was wondering how to still take in there message even if they dont send an image

slate swan
radiant parrot
slate swan
acoustic parcel
#

does anyne know why this is happening

slate swan
#
attachment = message.attachments[0].attachments if message.attachments else None

this will grab the first image as an Attachment object from the message else it'll be set to None if there is no image in the message

slate swan
slate swan
#

kill 1

#

with a space smh

acoustic parcel
#

oh ty

radiant parrot
#

as it gets stuck in a loop to send the embed

#
    if message.content is not None and message.attachments and message_channel in 1017792577740734536 or 1018468004121542716: # Add message content to list
        msg_list.append(message.content)
        attachment = message.attachments[0].attachments if message.attachments else None
        await message.delete()
        print(msg_list)
        comhelper = '<@&889878315089932328>'
        staff = '<@&810238562053914695>'
        admin = '<@&811310504471035935>'
        channel = client.get_channel(1017118446284177419) # channel where checked if post is good
        embed = discord.Embed(title=f'Message detected in #{channel_sent_in}', color = 10181046)
        embed.add_field(name='Message: ', value=f'{message.content}')
        embed.add_field(name='User: ', value=f'{message.author}')
        embed.set_image(url= attachment)
        embed.set_footer(text=f'Provided by Donks#1048 • {current_time}')
        await channel.send(f"Here: {comhelper + staff + admin}")
        await channel.send(embed=embed, view=view)```
naive briar
#

Uh

#

The first thing is that you're using or in the wrong way

radiant parrot
#

How come 🙂

naive briar
#

!or

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
acoustic parcel
#

for some reason when I run this code, nothing happens, but when I try using something like on_message it works

from discord.ext import commands

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


@client.command()
async def test(ctx):
  await ctx.send("hi")
  print("ok")



client.run(token)```
naive briar
acoustic parcel
#

alr ill give that a try

#

yeah it worked tysm

radiant parrot
# naive briar !or

how would i now fix the issue of the skipping the embed if attactment is none

naive briar
#

Uh

#

Just check if it's not none before setting it

if not attachment:
    embed.set_image(url="attachment://preview.png")
radiant parrot
#

ah thank you

#

also py if message.content is not None and message.attachments and message_channel in [1017792577740734536, 1018468004121542716]:

#

Seems to not be picking up messages in the channels

naive briar
#

Well

#

You can remove message.attachments

#

From that

radiant parrot
#

Yes 🙂

silk pasture
#
import discord
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    guild = await client.fetch_guild(768888081121542245)    
    print(guild.member_count)

why is the Output None?
I have enabled the GUILD_MEMBERS intent in the Developer Portal

slate swan
#

it's erroring in the

if result == None:
  ...
  category.id #category is None as it wasn't passed during command invocation
vocal snow
#

Why aren't you using subcommands

honest shoal
#

how can I check that the one who is clicking the button executed the command?

dark pine
#

is it possible to make the bot give a specific role?

dark pine
#

like, when player have x give em y role

honest shoal
#

yes

dark pine
#

how hard it will be for someone who has never code any discord bot?
But i have already build a bot with .add .remove .... and other commands, of virtual points

vocal snow
#

Try it out, if you know python basics it won't be hard

light jungle
#

how to check with "await_for" if a person has replied to a message?

#

who suddenly did not understand where the "reply" item is right-click on the message and there will be an answer

winged coral
#

wait for "message"

#

Trying to wait for a message after command was called?

@bot.command()
async def command(ctx):
    await ctx.send("Type: `hello`")

    def check(m):
        return m.content == 'hello' and m.channel.id == ctx.channel.id

    try: # wait_for will return Message when check function returns True
        msg = await bot.wait_for('message', check=check, timeout=10)
    except asyncio.TimeoutError: # wait_for raised TimeoutError after 10 seconds
        await ctx.send("10 seconds has passed, timeout.")
    else:
        await ctx.send(f'Hello `{msg.author}`!')
light jungle
light jungle
maiden fable
radiant parrot
feral frost
#

guys

#

what path do i use if i put a json file inside another folder ?

#

is this the close button

#

ok

#

ok

#

what do the other buttons do ?

#

and do they work

#

hmm ok

radiant parrot
light jungle
#

how to fix?

dull terrace
ionic edge
#
IndexError: list index out of range```
#
    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload):
        emoji = payload.emoji
        guild = self.client.get_guild(payload.guild_id)
        channel = self.client.get_channel(payload.channel_id)
        message = await channel.fetch_message(payload.message_id)
        if emoji.name == "⭐":
            cursor = self.client.db.cursor()
            cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={guild.id}")
            starData= cursor.fetchone()
            if starData:
                starLimit = starData[2]
                starboardChannel = self.client.get_channel(starData[1])
                if starboardChannel is None:
                    return
                else:
                    if message.channel == starboardChannel:
                        return
                    else:
                        if message.author == self.client.user:
                            return
                        else:
                            if message.author == guild.me:
                                return
                            else:
                                if message.author.bot:
                                    return
                                else:
                                    if message.author == payload.member:
                                        return
                                    else:
                                        if message.reactions[0].count >= starLimit:
                                            async for message in starboardChannel.history(limit=100):
                                                if message.embeds:
                                                    if message.embeds[0].footer.text == f"Message ID: {message.id}":
                                                        await message.embeds[0].edit(description=f"**`⭐`{message.reactions[0].count}**")
                                                    else:
                                                        embed = discord.Embed(title=f"⭐  {message.reactions[0].count}  ", description=f"[Jump to message!]({message.jump_url})", color=0x03befc)
                                                        embed.add_field(name="Message Content", value=message.content, inline=False)
                                                        embed.set_footer(text=f"Message ID: {message.id}")
                                                        embed.set_author(name=message.author.name, icon_url=message.author.avatar)
                                                        embed.timestamp = message.created_at
                                                        if message.attachments:
                                                            embed.set_image(url=message.attachments[0])
                                                            await starboardChannel.send(embed=embed)
            cursor.close()```
#

my code

dull terrace
ionic edge
#

it has

honest shoal
#

can someone explain this error

#
2022-09-11T16:13:07.874295+00:00 app[worker.1]: Traceback (most recent call last):
2022-09-11T16:13:07.874308+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py", line 1262, in process_application_commands
2022-09-11T16:13:07.874308+00:00 app[worker.1]:     await app_command.invoke(interaction)
2022-09-11T16:13:07.874310+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/disnake/ext/commands/base_core.py", line 415, in invoke
2022-09-11T16:13:07.874311+00:00 app[worker.1]:     raise CommandInvokeError(exc) from exc
2022-09-11T16:13:07.874325+00:00 app[worker.1]: disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
2022-09-11T16:13:07.874325+00:00 app[worker.1]: In data.components.0.components.0.label: This field is required```
dull terrace
honest shoal
#

label is name on the button, right?

dull terrace
#

yes

honest shoal
#

but I don't want name

#

just the emoji

dull terrace
#

are you fetching an emoji to put in it?

honest shoal
#

yes

dull terrace
#

could be that the emoji is not fetching properly and you're trying to do emoji=None

#

you can use just an emoji

honest shoal
#

just the emoji id there?

dull terrace
#

after where you've fetched the emoji, print it

#

see if it's None

honest shoal
#

it's not none

#

I'll print to conform

ionic edge
#
    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload):
        emoji = payload.emoji
        guild = self.client.get_guild(payload.guild_id)
        channel = self.client.get_channel(payload.channel_id)
        message = await channel.fetch_message(payload.message_id)
        if emoji.name == ":star:":
            cursor = self.client.db.cursor()
            cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={guild.id}")
            starData= cursor.fetchone()
            if starData:
                starLimit = starData[2]
                starboardChannel = self.client.get_channel(starData[1])
                if starboardChannel is None:
                    return
                else:
                    if message.channel == starboardChannel:
                        return
                    else:
                        if message.author == self.client.user:
                            return
                        else:
                            if message.author == guild.me:
                                return
                            else:
                                if message.author.bot:
                                    return
                                else:
                                    if message.author == payload.member:
                                        return
                                    else:
                                        if message.reactions[0].count >= starLimit:
                                            async for message in starboardChannel.history(limit=100):
                                                if message.embeds:
                                                    if message.embeds[0].footer.text == f"Message ID: {message.id}":
                                                        await message.embeds[0].edit(description=f"**`⭐`{message.reactions[0].count}**")
                                                    else:
                                                        embed = discord.Embed(title=f":star:  {message.reactions[0].count}  ", description=f"[Jump to message!]({message.jump_url})", color=0x03befc)
                                                        embed.add_field(name="Message Content", value=message.content, inline=False)
                                                        embed.set_footer(text=f"Message ID: {message.id}")
                                                        embed.set_author(name=message.author.name, icon_url=message.author.avatar)
                                                        embed.timestamp = message.created_at
                                                        if message.attachments:
                                                            embed.set_image(url=message.attachments[0])
                                                            await starboardChannel.send(embed=embed)
            cursor.close()```
dull terrace
#

is your bot a copy of starboard?

ionic edge
dull terrace
#
if starboardChannel is None:
                    return
                else:
                    if message.channel == starboardChannel:
                        return
                    else:
                        if message.author == self.client.user:
                            return
                        else:
                            if message.author == guild.me:
                                return
                            else:
                                if message.author.bot:
                                    return
                                else:
                                    if message.author == payload.member:
                                        return```
dude
ionic edge
#

and i want that if the messsage reaction get updated

#

then update the starboard channel message

honest shoal
#

yes it printed None

honest shoal
#

but that emoji exists

dull terrace
#
if (
  starboardChannel is None 
  or message.channel == starboardChannel 
  or message.author in (self.client.user, guild.me, payload.member)
  or message.author.bot 
 ):
  return
vale wing
dull terrace
#

hold on can make it better

honest shoal
vale wing
honest shoal
#

grumpchib why is it printing none

honest shoal
vale wing
#

What are your intents

honest shoal
#

intents = disnake.Intents.default()
intents.presences = True
intents.members = True
intents.message_content = True

vale wing
#

Just fyi you can use disnake.Intents.all() without need to enable those 3

austere vale
#
  #ping slash command
  @nextcord.slash_command(name='ping',description='Check the bot\'s ping!', guild_ids=[702824491667161160])
  async def ping(interaction:Interaction):
    embed=nextcord.Embed(title='Bot Ping')
    embed.add_field(name='My API latency is: ', value= f'{round(self.bot.latency * 1000)}ms')
    embed.set_footer(text=f'Ping requested by {interaction.user}', icon_url=interaction.user.display_url)
    await interaction.response.send_message(embed=embed)
```how do i fix this error?
honest shoal
#

but what about that emoji

dull terrace
vale wing
#

As for emoji, could you show how exactly you get it

honest shoal
vale wing
#

Mhm

#

I remember there was a problem recently

#

Not sure if it's about intents but hold on a sec here

honest shoal
#

😨

dull terrace
#

yeah i had an issue with emojis recently, trying to remember how i fixed it

ionic edge
#
    @commands.Cog.listener()
    async def on_raw_reaction_add(self, payload):
        emoji = payload.emoji
        guild = self.client.get_guild(payload.guild_id)
        channel = self.client.get_channel(payload.channel_id)
        message = await channel.fetch_message(payload.message_id)
        if emoji.name == "⭐":
            cursor = self.client.db.cursor()
            cursor.execute(f"SELECT * FROM starboard WHERE guild_id ={guild.id}")
            starData= cursor.fetchone()
            if starData:
                starLimit = starData[2]
                starboardChannel = self.client.get_channel(starData[1])
                if (starboardChannel is None or message.channel == starboardChannel   or message.author in (self.client.user, guild.me, payload.member)or message.author.bot ):
                    return
                if message.reactions[0].count >= starLimit:
                    async for message in starboardChannel.history(limit=100):
                        if message.embeds:
                            if message.embeds[0].footer.text == f"Message ID: {message.id}":
                                print("Message already in starboard.")
                            else:
                                if message.reactions[0].count >= starLimit:
                                    embed = discord.Embed(title=f"⭐  {message.reactions[0].count}  ", description=f"[Jump to message!]({message.jump_url})", color=0x03befc)
                                    embed.add_field(name="Message Content", value=message.content, inline=False)
                                    embed.set_footer(text=f"Message ID: {message.id}")
                                    embed.set_author(name=message.author.name, icon_url=message.author.avatar)
                                    embed.timestamp = message.created_at
                                    if message.attachments:
                                        embed.set_image(url=message.attachments[0])
                                    await starboardChannel.send(embed=embed)
            cursor.close()
honest shoal
#

please use pastebin dude

ionic edge
#

@dull terrace

vale wing
#

@honest shoal try this

intents = disnake.Intents.all()
print(intents.value & 1 << 3 == 1 << 3)```
dull terrace
#

if it's None then there might be a permissions problem idk

ionic edge
#

see

#

its coming

#

print is working

dull terrace
#

what does it print

light jungle
#

what attribute is needed for the bot to answer you? (I tried reply doesn't work)

vale wing
ionic edge
dull terrace
#

did you print message.reactions.count?

light jungle
ionic edge
light jungle
#

this is example

vale wing
#

!d nextcord.Interaction.send idk

unkempt canyonBOT
#

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

This is a shorthand function for helping in sending messages in response to an interaction. If the interaction has not been responded to, [`InteractionResponse.send_message()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.send_message "nextcord.InteractionResponse.send_message") is used. If the response [`is_done()`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.InteractionResponse.is_done "nextcord.InteractionResponse.is_done") then the message is sent via [`Interaction.followup`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Interaction.followup "nextcord.Interaction.followup") using [`Webhook.send`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Webhook.send "nextcord.Webhook.send") instead.
dull terrace
#

print message.reactions

vale wing
ionic edge
#

[<Reaction emoji='⭐' me=False count=2>]

vale wing
#

Now try getting emoji with Guild.get_emoji with guild it belongs to

ionic edge
#

@dull terrace

honest shoal
#

Ok

light jungle
vale wing
#

The send method?

#

Every interaction response can be considered a reply

#

Although real reply would be inter.message.reply but it would never respond to the interaction itself and it shouldn't happen

light jungle
#

no, I mean how in this example that the bot would directly respond to the message

dull terrace
#

not sure, doesn't make sense to me that it'd be able to find the index on the if statement a couple lines above and then fail later

vale wing
ionic edge
#
                    # async for message in starboardChannel.history(limit=20):
                    #     if message.embeds:
                    #         if message.embeds[0].footer.text == f"Message ID: {message.id}":
                    #             print("Message already in starboard.")
                    #         else:
                    #             if message.reactions[0].count >= starLimit:
                    embed = discord.Embed(title=f"⭐  {message.reactions[0].count}  ", description=f"[Jump to message!]({message.jump_url})", color=0x03befc)
                    embed.add_field(name="Message Content", value=message.content, inline=False)
                    embed.set_footer(text=f"Message ID: {message.id}")
                    embed.set_author(name=message.author.name, icon_url=message.author.avatar)
                    embed.timestamp = message.created_at
                    if message.attachments:
                        embed.set_image(url=message.attachments[0])
                    await starboardChannel.send(embed=embed)
            cursor.close()```
vale wing
#

!d discord.ext.commands.Context.reply

unkempt canyonBOT
#

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

A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") referenced by this context.

For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send "discord.ext.commands.Context.send").

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
ionic edge
#

if i do this it works but doesnt update

dull terrace
#

oh i see

light jungle
ionic edge
vale wing
crimson plover
#

how can i resolve this? the code works fine but want to get rid of this error..

@a2m.event
async def on_message(message):
    ChatString = message.content
    UserName, GameCommand, *rest = ChatString.split(":")
    print('UserName: ' + UserName)
    print('Command: ' + GameCommand.strip())
    print('Additional Arguements: ' + str(rest))    
    AdminRole = discord.utils.get(message.author.roles, name = "Admin")
    # MemberRole = discord.utils.get(message.author.roles, name = "Member")

    if message.author == a2m.user:
        return

    #Discord Admin Check
    if message.author.guild_permissions.administrator:
            #Xerp Check
        if message.content.startswith('Xerp:'):
            if ComPrefix + 'test' in GameCommand:
                await message.channel.send('Test Passed all Checks, Hello Xerp')
                return
        if ComPrefix + 'test' in GameCommand:
            await message.channel.send('Test Passed all Checks, Hello Admin')
            return
    #If user does not have the Admin Role.
    if not AdminRole:
        if ComPrefix + 'test' in GameCommand:
            await message.channel.send('Test Passed all Checks, Hello User')
            return

Traceback (most recent call last):
File "C:\Users\manes\Desktop\Zomboi A2M\A2M 9 - 7\env\lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\manes\Desktop\Zomboi A2M\A2M 9 - 7\a2m.py", line 169, in on_message
UserName, GameCommand, *rest = ChatString.split(":")
ValueError: not enough values to unpack (expected at least 2, got 1)

vale wing
#

You can't reply to slash command

#

You can only respond to it

dull terrace
#

async for message in starboardChannel.history(limit=100): how are you storing messages

vale wing
#

And it is done with inter.send

light jungle
dull terrace
#

why not just store the int value

#

is this even your code?

ionic edge
unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message").

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
vale wing
#

Just get the message object and use this

dull terrace
#

it's your code but you don't know...

ionic edge
#

why to store in int??

#

it will check the embed in the channel history

#

then it will check if the footer matches or not

honest shoal
dull terrace
#

just store the fields you need and not the whole message

vale wing
unkempt canyonBOT
#
No way, José.

No documentation found for the requested symbol.

vale wing
#

Oh sorry

#

Weird of them

#

!d discord.Guild.emojis

light jungle
unkempt canyonBOT
vale wing
# unkempt canyon

@honest shoal try printing these and see if anything prints at all

#

Meanwhile I am gonna check more docs

honest shoal
ionic edge
dull terrace
vale wing
honest shoal
#

bot got crashed anyway, I'll update the code

dull terrace
#

if i wanted to store emoji reaction counts for messages, i'd use the message id as a primary key in a database and then use a column for emoji_count

vale wing
#

Um why store them when you can just get them from discord 🤓

dull terrace
#

reduce api calls?

#

idk why they're doing it

vale wing
#

Well I doubt the emoji count would be needed so frequently

#

You could cache it anyway

dull terrace
#

looks like they're making a starboard type thing

#

or just copying the code tbh

vale wing
#

Long-term storage of something stored on discord is pointless imo

ionic edge
#

myself

clear onyx
#

Hey everyone

dull terrace
vale wing
#

Hello

vale wing
#

I meant cache is more suitable for this

dull terrace
#

until you need to restart the bot

vale wing
#

That's not really a problem

dull terrace
#

and you have to fetch thousands of messages

clear onyx
#

Does anyone know if one can make a bot do a voicecall when a message is sent? So but calls a person and gives code which they then have to type in to auth…

vale wing
#

Well depends

dull terrace
#

storage is cheap, why wouldn't you take advantage of it

vale wing
#

Data syncing is a thing

#

And it is often a headache

ionic edge
#

@dull terrace

#
Message ID: 1010598292624789554
None
Message ID: 1018527051122233465
Message ID: 1018527051122233465
Message ID: 1018527051122233465
Message ID: 1018527051122233465
Message ID: 1018527051122233465
Message ID: 1018526332428222546```
#
                        if message.embeds:
                            print(message.embeds[0].footer.text)
                            if message.embeds.footer.text == f"Message ID: {message.id}":
                                print("Message already in starboard.")
                                return```
#

if i do this

ionic edge
#

but the message already in starboard is not printing even if it is there

dull terrace
#

okay so one of the messages doesn't exist

#

i guess just do

async for message in starboardChannel.history(limit=20):
  if message.id is None:
    continue
  if message.embeds:
    print(message.embeds[0].footer.text)
    if message.embeds.footer.text == f"Message ID: {message.id}":
    print("Message already in starboard.")
    return```
honest shoal
#

I messed up really hard

#

is there any fetch_emoji()?

errant coral
#

Anyone know how to make so a discord bot sends a embed with a question and then when someone aswere it will see that and send another embed with another question?

light jungle
#

How can I make a custom prefix in the "nextcord" fork?

errant coral
honest shoal
#

idk nextcord

dull terrace
honest shoal
# errant coral Help me
  1. make questions with answers
  2. send questions
  3. check for answers in users msg
  4. then post another ques.
honest shoal
#

there's fetch_sticker but no fetch_emoji

errant coral
dull terrace
honest shoal
dull terrace
#

is your bot in the server with the emoji, is the id correct, does your bot have the right permissions

light jungle
#

is it possible to check whether the person answered through the "reply" button or just wrote a message:

ionic edge
#
                    async for message in starboardChannel.history(limit=20):
                        if message.id is None:
                            continue
                        if message.embeds:
                            print(message.embeds[0].footer.text)
                            if message.embeds[0].footer.text == f"Message ID: {message.id}":
                                print("Message already in starboard.")
                                return
                            
                            else:
                                embed = discord.Embed(title="Starboard", description=f"**`⭐`{message.reactions[0].count}**", color=0x03befc)
                                embed.add_field(name="Message", value=message.content, inline=False)
                                embed.set_author(name=message.author, icon_url=message.author.avatar_url)
                                embed.set_footer(text=f"Message ID: {message.id}")
                                await starboardChannel.send(embed=embed)
                                return```
errant coral
ionic edge
#

again same error

#
    embed = discord.Embed(title="Starboard", description=f"**`⭐`{message.reactions[0].count}**", color=0x03befc)
IndexError: list index out of range```
honest shoal
dull knot
#

Is there a method to look for the channel's very first message? I'd like to know. And the documentations as well pls.

ionic edge
#

if i add this

#
                                embed = discord.Embed(title="Starboard", description=f"**`⭐`{message.reactions[0].count}**", color=0x03befc)
                                embed.add_field(name="Message", value=message.content, inline=False)
                                embed.set_author(name=message.author, icon_url=message.author.avatar_url)
                                embed.set_footer(text=f"Message ID: {message.id}")
                                await starboardChannel.send(embed=embed)
                                return```
honest shoal
dull terrace
honest shoal
dull terrace
#

i'd assume it's a silly mistake that you're missing

#

double check everything

errant coral
# honest shoal then how are you planning to do

im making a application system and i want to answere the question in chat so i need help with making the bot see the aswere the person write and then send another embed with another question

honest shoal
dull terrace
#

so you have the emoji right there

#

what's the issue

honest shoal
#

I'm thinking to give up and use a default emoji instead

dull terrace
#

if get_emoji was broken you'd print None

#

you have the emoji and just need to use it?

honest shoal
#

and threw an error which I posted first

dull terrace
#

but you just showed the code and it printed an emoji object?

honest shoal
honest shoal
dull terrace
errant coral
honest shoal
dull terrace
#

oh also akg, make sure your bot is ready

#

if you try to fetch it before on_ready() it'll return None

honest shoal
#

OH

#

still doesn't worl

dark pine
#

im trying to setup my bot on pebblehost and got this error

winged coral
#

"Pebblehost" does not have discord.py installed for whatever interpreter you're using

dark pine
#

also i got import discord

winged coral
#

Do you understand the difference between running python locally and on a virtual server's python installation?

#

The interpreters are different and do not have the same 3rd party libraries installed

dark pine
#

yeah, i have the package downloaded myself in cmd but in pebble i had download the packages too

winged coral
#

Well I can't debug for you but the error indicates it isn't

#

Perhaps the versions are mismatched

slate swan
#

pretty sure you don't need to install dependencies in peeblehost yourself
you just provide a requirements.txt with all the deps

dark pine
slate swan
#

can you show us a screenshot of your peeblehost setup

dark pine
#

yeah, for sure

#

ok i got it running now the requirements.txt wasnt in

#

but i dont understand what is it for?

#

i just found it in stackflows but no explanation

slate swan
#

welp, as the name suggests it's a file containing a list of libraries required to install

crimson plover
#

So does anyone know how i can go about handling my error? or point me in the direction of fixing it? as i said the code works proper as it ignores the exception but im not sure how to figure out how to check for it

vocal snow
#

What's the error

crimson plover
vocal snow
#

If you're on dpy 2.0 make sure your message content intents are enabled. And remember that on_message goes through all messages the bot can see

dark pine
#

Suggestions on how i can make the bot give roles according to points

feral frost
#

anyone knows a timeout command ?

#

a simple one

#

? pls

slate swan
#

hi so basically i started coding like 1 mintue ago for the first time and i wanna make this thing where when u open the file it turns the bot online
i did the first part but how do i put that when i turn on the file the bot runs
import discord
from discord.ext import commands
import random
from discord import Permissions
from colorama import Fore, Style
import asyncio
token = "Bot token"

feral frost
#

but this at the end

#

bot.run(token)

#

intents = Intents.default()
intents.message_content = True
BOT_PREFIX = "$"
bot = commands.Bot(command_prefix=BOT_PREFIX, intents=intents)

this under the imports

#

and an on_ready event to see if the bot is online

feral frost
#

?

faint sapphire
#
async def wfl(ctx, arg1):```

when theres a space in the input, arg1 will only take the first argument when calling this command
how do i take an infinity of arguments
primal token
#

just add it before arg1

faint sapphire
#

async def wfl(ctx, *args?)?

primal token
feral frost
#

idk

primal token
#
@bot.command()
async def wfl(ctx, *, arg1):

e.g

faint sapphire
#

oh ok thank you

#

with commands, is it possible to do .lower() to the command the user uses

primal token
#

pardon? like an alias?

faint sapphire
#

or is the only way to make multiple functions

primal token
#

!d discord.ext.commands.Command.aliases

unkempt canyonBOT
faint sapphire
#

id like Wfl, and wfl to be the same command, but making a diff function sounds like a caveman practice

#

ok thanks

primal token
#

yep an alias!

plush rock
#

is there a way to toggle an "on_message" function only after a specific command has been used?

primal token
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
slate swan
#

hi i wanna make a tool like .exe when u open it runs the bot

#

i just started coding today so idk can someone do it il send code

plush rock
#

I'll take a look at it, ty!

primal token
slate swan
#

ik wym

primal token
unkempt canyonBOT
#

PyInstaller bundles a Python application and all its dependencies into a single package.

slate swan
#

but i wanna connect it to a tool

#

like connect code to a exe and when i run exe bot turns on

primal token
#

but why exactly?

slate swan
#

its just for personal use

#

for a bot

primal token
#

!d os.system | which you can just invoke python from a command, you can just do it in python and then turn the python file to an executable with pyinstaller i wouldnt recommend it tho

unkempt canyonBOT
#

os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.

On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait "os.wait").
faint sapphire
#
@bot.command(aliases=['Wfl', 'WFl', 'WFL', 'wFL', 'wfL', 'wFl'])
async def wfl(ctx, *, arg1):
```i understood with a forum
it rly isnt clear how to implement it in the documentation :/
at least the docs let you know of whats possible
primal token
#

no need for the brackets in the function name

faint sapphire
#

ah yh my bad i was testing someting

vale wing
#

What library is this

#

Db library

#

Why did it suddenly get so popular 🤔

#

Probably because of some yt tutorial

faint sapphire
#

u supposed to do result = fetch...ect

#

that is normal
it gives 1, 2 or 3 as output for saying it updated, or not, or added a new thing in the db

vale wing
#
  1. Don't use f-strings, use placeholders just like you did first time
  2. I don't really know how exactly is it done in aiomysql, but I suspect that you need to do something like res = await cur.fetchone(...) instead of execute
vale wing
#

Sorry what

vale wing
faint sapphire
#

wow

#

nice thanks

vale wing
#

Np

weary flume
#

how do i replace things in a text file

faint sapphire
#

and it allows u to change stuff

weary flume
#

ok ill look into it

#

ty

spark igloo
#
from discord.utils import get

@bot.command(pass_context=True)
async def purge_members(ctx):
    for member in ctx.message.server.members:
      if not get(member.roles, name='calls'):
        else not get(members.roles, name='notifications'):
            await bot.kick(member)```
#

guys this would kick members without the calls and notifications role right?

sick birch
#

You can check if the user doesn't have the calls and notifications role like so:

if not (get(member.roles, name="calls") and get(member.roles, name="notifications")):
  # kick user
spark igloo
#

oh yea alr

severe rampart
#

@spark igloo also, what is else not

#

never really seen that before

spark igloo
severe rampart
#

oh mkay

sick birch
#

I'm guessing they mixed up elifs and elses

#

ugh my system clock is fucked again i need to figure out how to fix it

spark igloo
#

@sick birch

@client.event()
async def on_ready(ctx):
    for member in ctx.message.server.members:
      if not (get(member.roles, name="calls") and get(member.roles, name="notifications")):
            await client.kick(member)```

This would make it so whenever i just run the bot it runs that code ye?
sick birch
#

Should be @client.event

#

Doing this in on_ready is not really a good idea though

spark igloo
light jungle
#

the question is can I make a check if the person answered the message of the bot using the "reply" button?

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
light jungle
#

why do you need it?

rocky trench
#

I thought u were a diff person than the person who asked the question, got a bit confused

#

U could use it for a giveaway bot where u wait for a message in the channel the bot is in, so they don't need to add it as a parameter

crimson plover
rocky trench
maiden chasm
#

!d commands

#

Can someone teach me how to make a discord bot dm me pls

maiden chasm
crimson plover
feral lichen
dull knot
#

How can I turn this (1st pic) into this (2nd Pic)?

#

My code goes like this ```py
ServerInfoEmbed.add_field(name="Creation:", value=f"{inter.guild.created_at}", inline=True)

#

So that the Bot will only say: days, weeks, months or years instead of being overly specific

#

Also, help me out guys.. Will be going offline in a few more bit

dull knot
#

I guess just tell me what method to use or what to change. For now, I gtg lol. I'll check replies later

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...
vale wing
hybrid seal
#

I like postgres

vocal snow
paper sluice
#

f' <t:{ctx.guild.created_at.timestamp():.0f}:R>

vale wing
#

Because indians always have been here and I started to frequently see mysql questions here not really long time ago

vocal snow
#

True but a discord bot youtube tutorial using a database seems impossible

vale wing
#

Yes lmao

eternal fox
#

How can i fix this

vale wing
slate swan
#

can anyone help me with pymongo, i have the whole adding things to database working but when i try to use the collection.find then and print 'snippet' it just ends up printing this <pymongo.cursor.Cursor object at 0x00000252D5DA3D60> and idk how im supposed to print the snippet data. if anyone could help id appreciate it

vale wing
left idol
#

n['snippet'] should give the value

frail sedge
#

hello can anyone help me send a body request to a website?

#

conn.request("POST", "/giverole", json.dumps({"discord_id": %s, "account_name": username}), headers)

maiden fable
#

What's conn?

vocal snow
#

the %s in the dict wouldn't valid syntax

glad cradle
#

Read the error

#

!d discord.ext.commands.Bot.run

unkempt canyonBOT
#

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.start "discord.ext.commands.Bot.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect "discord.ext.commands.Bot.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login").

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
vocal snow
#

discord doesn't allow selfbots

vale wing
#

No selfbots xdxd

vocal snow
#

why u delet pithink

vale wing
#

Discord changed delete button relative placement, now my kinematic memory always makes me press copy

#

Is there a way to disable confirmation message on mobile

#

Like I don't have shift here

digital charm
#

I have made the bracket with the error bold

pulsar solstice
#
@bot.command()
async def steal(ctx, member:discord.Member):
    if member == None:
        guild = ctx.guild
        member = random.choice(guild.members)
    await open_account(ctx.author)
    await open_account(member)
    users = await get_bank_data()
    member_account_val = users[str(member.id)]["Wallet"] - 50
    if member_account_val == 0:
        await ctx.send(f"{member.mention} caught you stealing them")
    amount = random.randrange(0, member_account_val)

    users[str(member.id)]["Wallet"] -= amount
    users[str(ctx.author.id)]["Wallet"] += amount```
#

this is my code

#

I am getting a error in the random range line

#

so basicly I am making a economy bot

pulsar solstice
#

that stores the user id and the value in a josn file

pulsar solstice
digital charm
pulsar solstice
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: empty range for randrange() (0, -50, -50)  
#

this is the error

digital charm
pulsar solstice
#

I did it in like 15 - 20 mins

#

u think am lying

#

just ask me something

digital charm
pulsar solstice
#

bruh can u please help me with this random range error

scarlet sorrel
#

How do i get the media link to messages that have file attachments?

tidal hawk
digital charm
scarlet sorrel
#

Wat?

digital charm
#

of the embed or the msg

scarlet sorrel
#

Embed

pulsar solstice
digital charm
# scarlet sorrel Embed
await ctx.send(file=discord.file(fp="(your_file_name).jpg", filename="image.jpg"))
#.jpg is just an example, it can be what the file type is```
scarlet sorrel
#

Bro

digital charm
digital charm
digital charm
naive briar
pulsar solstice
#

how??

#

can u tell me some alternative tehen?

naive briar
tidal hawk
scarlet sorrel
spark igloo
#
@bot.command()
async def noroleskick(ctx):
    # iterate through guild members and kick members with only 1 (@everyone) role
    # increase kicked counter +1 for each kicked member
    guild_members = ctx.guild.members
    kicked = 0
    for member in guild_members:
        if len(member.roles) == 2:
            # print(member.display_name)
            await member.kick()
            kicked += 1
    # If any members were kicked, send message with number of kicked members
    if kicked > 0:
            await ctx.send(f'{kicked} members were kicked from the server.')

This would kick members with the @ everyone and @ members role yeah? Basically if they have 2 roles it would kick em

pulsar solstice
#

???

naive briar
pulsar solstice
tidal hawk
#
    # if user has postive amount of balance
    amount = random.randint(0, member_accont_val)    ```
naive briar
#

You can just check if the number is lower than 1

pulsar solstice
tidal hawk
#

Damn, most of these questions are non discord bot related xD

pulsar solstice
#

don't worry about the lines

#

i will fix it later

spark igloo
tidal hawk
#

Try it without kicking actually

spark igloo
#

alr

#

i will just print that x members have 2 roles

tidal hawk
#

You can get a member object and just check his roles

digital charm
#

main.py

async def b(user:discord.User):
    db = await aiosqlite.connect("bal.db")
    cursor=await db.cursor()
    await cursor.execute(f"SELECT * FROM Balance WHERE user_id = {user.id} ")

    if result:
        return

    if not result:
        await cursor.execute(f"INSERT INTO bal(user_id, cash, crystals, event_pearls, weapon_shards, fusion_earring, merging_stones, enhancing_stones) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", (user.id, 500, 0, 0, 0, 0, 0, 0, 0))

        await db.commit()
        await cursor.close()
        await db.close()

@bot.command(aliases=['bal'])
async def balance(ctx, user:discord.User=None):
    if user is None:
        user = ctx.author

    await b(user=user)

    db = await aiosqlite.connect("bal.db")
    cursor = await db.cursor()
    await cursor.execute(f"SELECT * FROM Balance WHERE user_id = {user.id} ")

    balem=discord.Embed(description=f"**{user.metion}'s balance**", color=discord.Color.blue())
    balem.add_field(name="Cash:", value=f"{result[1]}", inline=False)
    balem.add_field(name="crystals:", value=f"{result[2]}", inline=False)
    balem.add_field(name="event pearls:", value=f"{result[3]}", inline=False)
    balem.add_field(name="weapon shards:", value=f"{result[4]}", inline=False)
    balem.add_field(name="fusion earring:", value=f"{result[5]}", inline=False)
    balem.add_field(name="merging stones:", value=f"{result[6]}", inline=False)
    balem.add_field(name="enhancing stones:", value=f"{result[7]}", inline=False)
    await ctx.send(embed=balem)
    ```
No error with the code itself but when I run the script (server_prefix) bal nothing happends, it doesn't give any errors, nor does it update send an embed, nor does the db get updated
#

PS - The db is aiosqlite

naive briar
#

Try changing discord.User to discord.Member

digital charm
naive briar
#

Did it work?

digital charm
#

nope

naive briar
#

Hmmm

#

Do you have intent members and message_content turned on?

digital charm
#

ye, but lemme just check

tidal hawk
#

Add some prints, so you can see where the code stops ig

radiant parrot
#

how do i fix it crashing when only an image is sent ```py
@client.event
async def on_message(message):
channel_final = client.get_channel(942848242616516638)
channel_final_mi = client.get_channel(640107632690200587)# channel to ping message if approved
button1 = Button(label="Approve!",style=discord.ButtonStyle.green)
button3 = Button(label="Disapprove - No Mute", style=discord.ButtonStyle.blurple)
button2 = Button(label="Disapprove!",style=discord.ButtonStyle.red)
view = View()
view.add_item(button1)
view.add_item(button3)
view.add_item(button2)
message_channel = message.channel.id
user_id = message.author.id
channel_sent_in = message.channel
# Check if message has content

if message.content is not None and message_channel in [1017792577740734536, 1018468004121542716]: # Add message content to list
    msg_list.append(message.content)
    await message.delete()
    print(msg_list)
    comhelper = '<@&889878315089932328>'
    staff = '<@&810238562053914695>'
    admin = '<@&811310504471035935>'
    channel = client.get_channel(1017118446284177419) # channel where checked if post is good
    embed = discord.Embed(title=f'Message detected in #{channel_sent_in}', color = 10181046)
    embed.add_field(name='Message: ', value=f'{message.content}')
    embed.add_field(name='User: ', value=f'{message.author}')
    embed.set_image(url=message.attachments[0].url if message.attachments else None)
    embed.set_footer(text=f'Provided by Donks#1048 • {current_time}')
    await channel.send(f"Here: {comhelper + staff + admin}")
    await channel.send(embed=embed, view=view)
digital charm
digital charm
naive briar
#

Yup

radiant parrot
radiant parrot
digital charm
#

same thing

naive briar
digital charm
#

the file is .db, could that be an issue?

tidal hawk
#

start debugging

digital charm
naive briar
radiant parrot
#

its cause py embed.add_field(name='Message: ', value=f'{message.content}') embed.add_field(name='User: ', value=f'{message.author}')

#

these r not being filled if only image

naive briar
#

I don't think discord.Attachment has url property

#

Nvm it has pithink

radiant parrot
#

and miss code out

#

as if only an image is sent, message content wnt work

naive briar
#

It's because this line

radiant parrot
#

what would i change? 🙂

naive briar
#

Eh, just remove "message.content" from the if statement and check if the message has any content and put it in the field. If not, then put none instead

if message_channel in [...]:
   ...
   embed.add_field(
        name='Message: ',
        value=message.content if message.content else None,
    )
radiant parrot
naive briar
#

Can you show the code

#

And what's the error

radiant parrot
#

Ah it works now

#

If now no message is sent, how would i make it say something else?

naive briar
#

Just change from None to something else

embed.add_field(
    name='Message: ',
    value=message.content if message.content else 'Something else',
)
vale wing
unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
naive briar
#

True

hot prawn
#

import lightbulb
bot = lightbulb.BotApp(token="
", prefix="-")

@bot.command
@lightbulb.command("ping", "checks the bot is alive")
@lightbulb.implements(lightbulb.SlashCommand)
async def ping(ctx):
  await ctx.respond("Pong!")





bot.run()
#

My bot ain't replying :/

rare echo
tidal hawk
#

Very cursed

hot prawn
#

...

#

"hikari-lightbulb"

rare echo
tidal hawk
paper sluice
#

?

dull knot
# dull knot How can I turn this (1st pic) into this (2nd Pic)?

Alright am back. I asked the question (In reply)

and got this answer:
f' <t:{ctx.guild.created_at.timestamp():.0f}:R> (This worked btw)
But what does these parts of the code mean?
f' <t:{ctx.guild.created_at.timestamp():.0f}:R>

This was a first I've worked using datetime so I'm kinda dumb when it comes to these lol

naive briar
hot prawn
#

I was using nextcord

bold kernel
#

Hi everyone, what means this following error shard id heartbeat blocked

hot prawn
dull knot
dull knot
ashen perch
#

anyone got any experience with cloudfare hosting in terms of quality?

upbeat gust
ashen perch
#

Accord to discord dev logs they do. Cant show Atm as im replying on apple watch =3

tidal hawk
#

Weird flex

#

How do you use Discord on your watch tho? xd

slate swan
#

plus the command handling is done in a better way

#

especially for hybrid commands

paper sluice
slate swan
slate swan
slate swan
#

wait wdym by not replying, its a slash command...

honest shoal
#

Hi, my msg delete button is not working. Following is the error: console The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/disnake/ui/view.py", line 370, in _scheduled_task await item.callback(interaction) File "/app/main.py", line 322, in delete await inter.delete_original_message() File "/app/.heroku/python/lib/python3.10/site-packages/disnake/interactions/base.py", line 532, in delete_original_message raise InteractionNotResponded(self) from e disnake.errors.InteractionNotResponded: This interaction hasn't been responded to yetAnd this is the code:```py
class Delete(disnake.ui.View):
def init(self, inter: disnake.ApplicationCommandInteraction):
super().init(timeout=43200)
self.inter = inter
@disnake.ui.button(emoji=jot, custom_id='delbutton')
async def delete(self, button: disnake.ui.Button, inter: disnake.MessageInteraction):
if self.inter.author.id != inter.author.id:
return await inter.response.send_message("Hey! You can't do that!", ephemeral=True)

    await inter.delete_original_message()```
slate swan
honest shoal
#

is it inter: disnake.MessageInteraction thing?

quaint epoch
#

Yes

#

!d disnake.MessageInteraction

unkempt canyonBOT
#

class disnake.MessageInteraction```
Represents an interaction with a message component.

Current examples are buttons and dropdowns.

New in version 2.1.
honest shoal
drifting arrow
#

what database package should I use with discordpy?

#

In your buttons class, define init and put some default variables, such as "message" or whatever. and when you need to call it, parse it as a variable and set the message variable to the message itself.
then when the button is pressed, it edits the message with the new buttons

upbeat gust
#

or a new db

drifting arrow
#

yes then set your variables. like self.message etc

drifting arrow
#

I havent chosen a db yet

upbeat gust
drifting arrow
#

no

#
def __init__(self):
        super().__init__(timeout=None)
        self.message = ''
#

then when you want to add buttons do:

mybuttons = MyButtonsClass()
mymessage = await interactions...(view=mybuttons)
mybuttons.message = mymessage

then in the MyButtonsClass when a button is pressed, edit the message with a new view

#

Lemme quickly whip some shit up as an example. idk if im explaining it correctly

brazen raft
drifting arrow
#
import discord
from discord.ext import commands
from discord import app_commands

class test(commands.Cog):
    
    def __init__(self, client):
        print("[Cog] My Test has been initiated")
        self.client = client


    @app_commands.command(name="test", description="test")
    async def test(self, interaction: discord.Interaction):
        mybuttons = AnswerButtons()
        mymessage = await interaction.response.send_message("Hello World", view=mybuttons)
        mybuttons.message = mymessage

      
class AnswerButtons(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.message = ''
        
    @discord.ui.button(label="Answer this question.", style=discord.ButtonStyle.green)
    async def answer(self, interaction: discord.Interaction, button: discord.ui.Button):
        newbuttons = NewButtons()
        message = await interaction.message.edit(content="Nope.", view=newbuttons)
        newbuttons.message = message
        
        
class NewButtons(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.message = ''
        
    @discord.ui.button(label="Go Back", style=discord.ButtonStyle.green)
    async def goback(self, interaction: discord.Interaction, button: discord.ui.Button):
        newbuttons = AnswerButtons()
        message = await interaction.message.edit(content="Hello", view=newbuttons)
        newbuttons.message = message
        
async def setup(client):
    await client.add_cog(test(client))
#

ofc this will result in an interaction failed. so you may need to do a interaction response

#

maybe like "await interaction.response.send_message("Thanks")" and delete it right away? idk

#

but it works

#

oh wait

#

it's await interaction.message.edit_message lol

#

not await interaction.message.edit

#

Checked some older code that does something similar coz I was wondering how I handled the interaction thing, and apparently I wrote this code wrong xD

#

yeah so it's just this:

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

class test(commands.Cog):
    
    def __init__(self, client):
        print("[Cog] My Test has been initiated")
        self.client = client


    @app_commands.command(name="test", description="test")
    async def test(self, interaction: discord.Interaction):
        mybuttons = AnswerButtons()
        mymessage = await interaction.response.send_message("Hello World", view=mybuttons)
        mybuttons.message = mymessage

      
class AnswerButtons(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.message = ''
        
    @discord.ui.button(label="Answer this question.", style=discord.ButtonStyle.green)
    async def answer(self, interaction: discord.Interaction, button: discord.ui.Button):
        newbuttons = NewButtons()
        message = await interaction.response.edit_message(content="Nope.", view=newbuttons)
        newbuttons.message = message
        
        
class NewButtons(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.message = ''
        
    @discord.ui.button(label="Go Back", style=discord.ButtonStyle.green)
    async def goback(self, interaction: discord.Interaction, button: discord.ui.Button):
        newbuttons = AnswerButtons()
        message = await interaction.response.edit_message(content="Hello", view=newbuttons)
        newbuttons.message = message
        
async def setup(client):
    await client.add_cog(test(client))
light violet
#

How do i use slash and prefix command at same time, i mean that i want to use a command as slash and prefixed with out writing the code two times

drifting arrow
#

Put the code itself into a function, and have the commands redirect to the function

#
@app_commands.command(name="test", description="test")
async def test(self, interaction: discord.Interaction):
    await self.mycodefunction()
@commands.command()
async def test2(self, ctx):
    await self.mycodefunction()

async def mycodefunction(self):
    mycode goes here.
```@light violet
#

Alternatively if you want, create a separate class entirely

light violet
#

Ok

#

Thnx

drifting arrow
#

Is it possible to do a command like /tableflip? where it appends to my message?

#

Like, you know how when you do the /tableflip command it appends that stuff to the end of your message. Can I make other commands?

light violet
#

How do i use hybrid command

#

No reponse is got through slash

drifting arrow
paper sluice
#

!d discord.ext.commands.Bot.hybrid_command

unkempt canyonBOT
#

@hybrid_command(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
drifting arrow
#

you

#

wot?! thats a thing?!

paper sluice
#

yea

drifting arrow
#

thats neat

maiden chasm
#

I wanna make a casino bot so how can I do it when I type .money that shows the money of a player he earned

drifting arrow
maiden chasm
#

Im a really really beginner