#discord-bots

1 messages ยท Page 738 of 1

slate swan
#

You did somewhere

message = "some string"
silver magnet
#

if ctx.message.channel.name == "mod-chat":
closest thing i can find to that

slate swan
#

That's not the problem.

#

Somewhere you've overwritten the message variable.

#

And did message = ...

silver magnet
#

ill try finding where because pretty sure i didnt do it on purpose

#

outside that block of code there isnt anything that necessarily overwrites message

#

or inside it

slate swan
#

There definitely is

silver magnet
#

or anywhere in the code look ill send

from discord.ext import commands

print(discord.__version__)

client = commands.Bot(command_prefix=",,")
TOKEN = "tokenishere"


@client.event
async def on_ready():
    print("logged as {0.user}".format(client))


@client.event
async def on_message(message):
    if message.author == client.user:
        return
    else:
        if message.content.lower() == "hello":
            await message.channel.send(f"hello {message.author.name}!")
        elif message.content.lower() == "hi":
            await message.channel.send(f"hello {message.author.name}!")
        elif message.content.lower() == "bye":
            await message.channel.send(f"goodbye {message.author.name}!")
        elif message.content.lower() == "goodbye":
            await message.channel.send(f"goodbye {message.author.name}!")
    await client.process_commands(message)


@client.command()
async def ping(ctx):
    await ctx.channel.send(f"In milliseconds: {round(client.latency * 1000)}")


@client.command()
async def say(ctx, *, message=None):
    if message is None:
        await ctx.send("Argument error")
    await ctx.message.delete()
    await ctx.send(f"{message}")


@client.command()
async def poll(ctx, *, message=None):
    if ctx.message.channel.name == "mod-chat":
        if message is None:
            mes = await ctx.send("Argument error")
            return
        await ctx.send(f"<@&role-id>, `{message}`")
        if message.author == client.user:
            if "<@&role-id>," in message.content:
                await message.add_reaction(":thumbsup:")
            else:
                return
        else:
            return
    else:
        return


client.run(TOKEN)
slate swan
#

Well, message is a parameter.

#

You probably want to use ctx.message everywhere instead of message in your poll command.

#

Besides when you need the argument you give.

#

Example here:

#

There you need to keep it

silver magnet
#

it seems to not add reactions still

slate swan
#

Hi I am "trying" to make an event for when ** only I** sends an int in a specific message the bot adds on a number then sends the message, so bassically just counting back and fourth between me and the bot. This is what I have so far but I 99% it is incorrect.

@bot.event
async def on_message(message):
    counting_channel = await bot.fetch_channel(822931755681841162)
    if message.channel.id == 822931755681841162 and message.author.id == 396620060531228672 and message.context is int:
        await counting_channel.send(message.context+1)
silver magnet
#

and i did use the raw emote

slate swan
#

It should appear like that

await message.add_reaction("๐Ÿ‘")

and not like that

await message.add_reaction(":thumbsup:")
silver magnet
slate swan
#

The code your sent proves the opposite.

slate swan
silver magnet
slate swan
#

Well, are you sending <@&role-id>?

slate swan
slate swan
silver magnet
#

if thats what youre meaning

slate swan
#

Well then it's normal it won't work now xD

slate swan
silver magnet
#

it does send the message without flaws it just doesnt add reactions

slate swan
slate swan
# silver magnet

You're checking if the author of the message if your bot. It will never be true.

#

The message author when executing a command is always you.

silver magnet
#

oh. i tried to make it detect it's own message so it adds the reaction to that

slate swan
#

So

if ctx.message.author == client.user

will always return False

barren fog
#

What difference discord py and nextcord

slate swan
#

discord.py is no longer being developed, nextcord continues development and has updates.

barren fog
#

Should I use it

slate swan
#

Your choice, not ours.

barren fog
#

Ok I will use js

slate swan
#

Sounds good

barren fog
slate swan
#

couldn't get an answer
switches languages

honest vessel
#

@slate swan any idea if possible and how i can make the coonsole runnig bot have partcial dynamic messages, and like a banner that is static ... atm all prints just go up n up

slate swan
#

Well, never did it as it's flooding the terminal for no reason. But you probably need to always clear and send the banner with the text.

round herald
#

hello?

honest vessel
#

hm

round herald
#

i am new to the server

barren fog
#

Leave

round herald
#

what?

barren fog
#

Nothing

round herald
#

like is this the place for bots?

barren fog
slate swan
#

For questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries.

round herald
maiden fable
round herald
#

how do i communicate with bots then?

#

am i supposed to ping em?

slate swan
#

Use #bot-commands

round herald
#

#bot-commands

#

?

slate swan
#

Go there, use commands and do something with them.

round herald
#

ok thanls i got it ๐Ÿ˜ƒ

#

*thanks

silver magnet
fervent shard
#

it's not sending the embed when i use the mute command nor give it the role.

@bot.command()
@commands.has_permissions(kick_members=True)
async def mute(ctx, member: discord.Member, *, reason=None):
    if member == ctx.author:
        em = discord.Embed(
            description=f"**you** cannot `mute` yourself", colour=discord.Colour.red()
        )
        await ctx.send(embed=em)
 
        guild = ctx.guild
        mutedRole = discord.utils.get(guild.roles, name="muted")
        await member.add_roles(mutedRole, reason=reason)
 
    else:
        em1 = discord.Embed(
            description=f"{member.mention} has been `muted` for **{reason}**",
            colour=discord.Colour.green(),
        )
    await ctx.send(embed=em)
 
    em2 = discord.Embed(
        description=f"**you** have been `muted` for **{reason}**", colour=0
    )
    await ctx.send(embed=em1)
    await member.send(embed=em2)
    list_of_muted_members.append(member)
    print(list_of_muted_members)
 
@bot.command()
@commands.has_permissions(kick_members=True)
async def unmute(ctx, member: discord.Member, reason=None):
 
    if member == ctx.author:
        em = discord.Embed(
            description=f"**you* cannot `unmute` yourself", colour=discord.Colour.red()
        )
        await ctx.send(embed=em)
 
    else:
        em2 = discord.Embed(
            description=f"{member.mention} has been `unmuted` for  **{reason}**",
            colour=discord.Colour.green(),
        )
        em3 = discord.Embed(
            description=f"**you** have been `unmuted` for  **{reason}**", colour=0
        )
        mutedRole = discord.utils.get(ctx.guild.roles, name="muted")
        await member.remove_roles(mutedRole)
        await member.send(embed=em3)
        await ctx.send(embed=em2)```
slate swan
slate swan
fervent shard
barren fog
#

TF He pay for Winrar

silver magnet
slate swan
#

!ot for other random talks please

unkempt canyonBOT
slate swan
#

As you need to execute your command, for example, like this:
!poll <@&585529568383860737>, something else here

silver magnet
#

did you really ping all the nitro boosters lol

slate swan
#

No, I don't have permissions.

silver magnet
#

oh yeah

frail notch
#

Ok... I don't get this error...

maiden fable
#

@frail notch your add_to_guild function

frail notch
maiden fable
#

Mhm

dreamy sluice
#

How do I make the bot send a message if I want it to do so in a on_message event?

#

the parameter doesn't have ctx, so I am confused.

potent spear
potent spear
frail notch
#

oh

dreamy sluice
potent spear
frail notch
#

so add_to_guild(code, userid) becomes add_to_guild(code, guild_id, userid)?

dreamy sluice
#

Not that, I am not referring to a command

potent spear
#

you just want to send a message in the same channel that message was sent in?

dreamy sluice
#

Yep.

potent spear
#

You're used to ctx.send, I suppose?

dreamy sluice
#

I don't have the ctx parameter, I am asking how to do it in a on_message event

#

imma send my code

potent spear
#

I'll give it to you via event

maiden fable
#

@dreamy sluice u can simply do ctx = await bot.get_context(message)

dreamy sluice
# dreamy sluice imma send my code
@bot.event
async def on_message(message):
  r = open("trigger_words.json", 'r')
  read = json.load(r)
  r.close()
  for i in read:
    if i["id"] == str(message.guild.id):
      dict = i["triggers"]
      for keys in dict:
        if str(message.content) == keys:
          #I want it to reply to the message in the paramater with dict[keys] here
maiden fable
#

This will get u the ctx object of the message

dreamy sluice
maiden fable
#

!d discord.ext.commands.Context for more information

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
dreamy sluice
#

:o

potent spear
#

he can just do await message.channel.send("hi")

frail notch
# potent spear correct

then that gives me this error... {"code": 50035, "errors": {"guild_id": {"_errors": [{"code": "NUMBER_TYPE_COERCE", "message": "Value \"<function guild_id at 0x0000000001D02C20>\" is not snowflake."}]}}, "message": "Invalid Form Body"}

potent spear
#

he doesn't need the context in an event

maiden fable
#

!d discord.ext.commands.Bot.get_context for more information

unkempt canyonBOT
#

await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Returns the invocation context from the message.

This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
maiden fable
#

My bad, this is the correct one

dreamy sluice
maiden fable
maiden fable
potent spear
dreamy sluice
dreamy sluice
#

Thanks :D

potent spear
#

ctx.send is an alias, it's basically ctx.channel.send, if that clears some stuff up for you

silver magnet
#

what do i need to write to make a bot add reactions? i tried await await ctx.message.add_reaction("raw emoji") but it doesn't seem to work in any way.

fervent shard
#

is there like a one line code that removes roles from a member that have send_messages permissions? (discord.py)

potent spear
potent spear
potent spear
silver magnet
# potent spear we need errors and concrete code to fix your issue

no errors. the code that runs the command is

async def poll(ctx, *, message=None):
    if ctx.message.channel.name == "mod-chat":
        if message is None:
            mes = await ctx.send("Argument error")
            return
        else:
            await ctx.send(f"<@&role-id>, `{message}`")
            if "<@&role-id>," in ctx.message.content:
                await ctx.message.add_reaction(":thumbsup:")
            else:
                return
    else:
        return```
maiden fable
silver magnet
potent spear
silver magnet
#

nope

potent spear
#

start debugging then

#

your if statement is just wrong

#

I'll give you the if statement

potent spear
#

if role_id in ctx.message.raw_role_mentions:

silver magnet
unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

maiden fable
#

This is cleaner

final iron
maiden fable
#

?

final iron
#

They remade the tag

dreamy sluice
#

Ok, I've got a new problem with my bot. I tried it's commands in different servers, and now it ceases to respond to other commands

final iron
#

It's a lot different now

maiden fable
#

O

dreamy sluice
maiden fable
#

With bot.event deco?

dreamy sluice
#

Yessir

#
@bot.event
async def on_message(message):
  r = open("trigger_words.json", 'r')
  read = json.load(r)
  r.close()
  for i in read:
    if i["id"] == str(message.guild.id):
      dict = i["triggers"]
      for keys in dict:
        if str(message.content) == keys:
          await message.reply(dict[keys])
#

This one

maiden fable
#

Change the deco to bot.listen()

silver magnet
# potent spear `if role_id in ctx.message.raw_role_mentions:`
async def poll(ctx, *, message=None):
    if ctx.message.channel.name == "mod-chat":
        if message is None:
            mes = await ctx.send("Argument error")
            return
        else:
            await ctx.send(f"<@&role-id>, `{message}`")
            if role-id in ctx.message.raw_role_mentions:
                await ctx.message.add_reaction(":thumbsup:")
            else:
                return
    else:
        return```
smth like this? please dont laugh at me lol
dreamy sluice
potent spear
maiden fable
#

Didn't I tell that only rn

final iron
frank tartan
#
@client.command()
async def toggleDM(ctx, status):
    user_id = ctx.author.id
    if status == "disable":
        noDM_list.remove(user_id)
        await ctx.reply("You can now recieve dm's from me.")
    elif status == "enable":
        noDM_list.append(user_id)
        await ctx.reply("You can no longer recieve dm's from me.")
    else:
        await ctx.reply("Please put either `disable` or `enable`")

@client.command()
async def dm(ctx, user:discord.Member,*,message=None):
    user_id = ctx.author.id
    if user in noDM_list:
        await ctx.reply("That user has diabled the ability for me to send them a dm. Send it yourself.")
        return
    else:
        await user.send(f"{message}\n\nSent by <@{user_id}>")
        await ctx.send("DM sent.")

that is my code.
when I do
toggleDM enable
dm cibere test
I get the dm, and when I do
toggleDM disable
dm cibere test
i also get the dm

why doesnt it block the dm, and how can i fix it? Please ping in reply

maiden fable
#

Wait, u asked the same question yesterday too, right?

frank tartan
maiden fable
#

Well I told u the issue

silver magnet
slate swan
#

how do I get the user mentions on on_message event?

frank tartan
potent spear
frank tartan
maiden fable
#

So, uhhh

final iron
#

Like you have already done

potent spear
maiden fable
#

PEP 8 is the style guide for Python

frank tartan
#

ty guys! it works now

maiden fable
#

The person just means that he should add spaces after the :

silver magnet
maiden fable
#

!pep 8 for more information (:

unkempt canyonBOT
#
**PEP 8 - Style Guide for Python Code**
Status

Active

Created

05-Jul-2001

Type

Process

final iron
silver magnet
#

right

slate swan
maiden fable
#

No

slate swan
#

then how do I get user?

maiden fable
#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

final iron
# silver magnet right

Then do what I said above and add the reaction to it i.e
var.add_reaction(...)
Don't use the naming I used. It might shadow some built in names

maiden fable
#

Actually it won't shadow

#

It's nothing (:

#

!d vars on the other side, is

unkempt canyonBOT
#

vars([object])```
Return the [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute for a module, class, instance, or any other object with a [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute.

Objects such as modules and instances have an updateable [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute; however, other objects may have write restrictions on their [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attributes (for example, classes use a [`types.MappingProxyType`](https://docs.python.org/3/library/types.html#types.MappingProxyType "types.MappingProxyType") to prevent direct dictionary updates).

Without an argument, [`vars()`](https://docs.python.org/3/library/functions.html#vars "vars") acts like [`locals()`](https://docs.python.org/3/library/functions.html#locals "locals"). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised if an object is specified but it doesnโ€™t have a [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute (for example, if its class defines the [`__slots__`](https://docs.python.org/3/reference/datamodel.html#object.__slots__ "object.__slots__") attribute).
final iron
#

I mean readability would still be bad

maiden fable
#

Ah, gotcha

silver magnet
#

also how do i do command checks? i searched it and it doesn't show anything

unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

frail notch
#

How can I fix dis

silver magnet
#

and i mean

#

return check(command)

slate swan
#

how do I get my full tag through member object?

silver magnet
slate swan
#

through member object

silver magnet
#

ah

slate swan
#

so message.member?

potent spear
slate swan
#

thanks

potent spear
#

show me the code and I'll tell you what's wrong with it

#

chances are, you're passing a function as an argument instead of an actual guild_id

maiden fable
#

Or u ain't calling a function

frail notch
# potent spear show me the code and I'll tell you what's wrong with it
def add_to_guild(access_token, guild_id, userid):
        url = f"{API_ENDPOINT}/guilds/{guild_id}/members/{userid}"
        data = {
        "access_token" : access_token,
    }
        headers = {
        "Authorization" : f"Bot {botToken}",
        'Content-Type': 'application/json'

    }
        response = requests.put(url=url, headers=headers, json=data)
        print(response.text)

code = exchange_code(excode)['access_token']
add_to_guild(code, guild_id, userid)
potent spear
potent spear
#

bingo

slate swan
#

what is the event for reactionadd?

potent spear
#

just rename that function to get_guild_id
then do guild_id = get_guild_id(guild_invite)

maiden fable
unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

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

Note

This doesnโ€™t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itโ€™s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
potent spear
# frail notch

there are other flaws in that code
for example
your first line in that method is defining a data dict, which you never use and simply overwrite

silver magnet
# unkempt canyon

how exactly do i check commands? i didnt really understand this because im stupid

maiden fable
#

member.timeout(time)

potent spear
#

this won't give you errors tho, but it's impractical

fervent shard
#

is there like a one line code that removes roles that have send_messages permissions? (discord.py)

frail notch
#

alright...

potent spear
#

we already answered that...
|| no, not in one line, unless you want to make it unreadable ||

fervent shard
#

like a mute command?

silver magnet
maiden fable
#

Check commands as in?

silver magnet
#

custom checks

#

i don't even really understand what theyre for but apparently i have to know and i dont know where i can learn them properly

#

eh, ill just give up at this point

slate swan
silver magnet
#

i don't know i just got told to make a command check

slate swan
#

Your main intention?

silver magnet
#

make a poll feature

#

you want more detail?

slate swan
#

like a poll feature which only users with some permissions can use right?

silver magnet
#

It's a poll feature for a mod chat in a server I'm in

slate swan
#

ah , so u want that to work only for that channel?

silver magnet
#

for making decisions

silver magnet
#

i tried using if/else to make sure it only works in the right channel

slate swan
#
async def cmd(...
      if ctx.channel.id == <mod channel ID>:
          # do stuff```
#

This should work

#

!custom-checks

unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

slate swan
#

And this is the check method to do that

#

Damn , the example is exactly what u need lol

maiden fable
#

Hahaha that's why I showed him the tag

silver magnet
#

"Expression expected"

#

gives this error in that line

boreal ravine
#

follow naming conventions

silver magnet
boreal ravine
silver magnet
#

managed to fix it by using () instead of ==

boreal ravine
#

๐Ÿ‘

silver magnet
#
async def poll(ctx, *, message=None):
    if ctx.channel.id(821116917753839627):
        if message is None:
            mes = await ctx.send("Argument error")
            return
        else:
            await ctx.send(f"<@&821111383939743754>, `{message}`")
            if 821111383939743754 in ctx.message.raw_role_mentions:
                await message.add_reaction(":thumbsup:")```
#

somethings wrong

cold sonnet
unkempt canyonBOT
cold sonnet
#

it's an attribute, not a function

silver magnet
#

do i have to add ctx or no?

cold sonnet
#

yes...

#

you have to

silver magnet
#

got it

cold sonnet
#

what

silver magnet
#

i think

#

not sure

cold sonnet
#

the way you just sent that

#

I do not think so

silver magnet
#

ah

#

im stupid

cold sonnet
#

it's right till this part

#

then you should just check if it's the right id

cold sonnet
#

if 821111383939743754 in ctx.message.raw_role_mentions: this is also wrong

#

!d discord.Message.raw_role_mentions

#

you know what

#

forget it

silver magnet
#

eh, i should just give up when i finish this

wanton cipher
#

I know I am kind of late to this, but what is a good alternative for discord.py since it's being shut down?

cold sonnet
#

di๐Ÿ

quick gust
#

I prefer disnake

slate swan
#
'Message' object has no attribute 'json'
cold sonnet
#

wth

wanton cipher
#

are there any major changes from discord.py to disnake?

cold sonnet
#

absolutely none

slate swan
#

looks prettyu much the same lol

cold sonnet
#

well slash commands

quick gust
#

No, just all instances of discord change to disnake

cold sonnet
#

but slash commands aren't a change, just an upgrade

wanton cipher
#

ok, well, I was recommended pycord but I'll use disnake, thank you for the help :D

quick gust
#

np

cold sonnet
silver magnet
final iron
slate swan
#
with open('premium.json','r') as f:
    data = json.load(f)
if f"{ctx.author.id}" in data:
cold sonnet
#

I don't think this is where you get the error

quick gust
#

Give the full traceback

cold sonnet
#

he's gone

silver magnet
#

does anyone know how to add reactions to a message your bot just sent?

cold sonnet
#

save the message in a variable

tacit token
#

Hello everyone! Can somebody help me? I would take a liking to it to make, that if impress onto a button on the message, let him not send one then yet, but let him modify the message

silver magnet
cold sonnet
#

send() doesn't only send the message, but it returns it

cold sonnet
#

meaning you can save it to a variable with the send() method

#

message = await ctx.send(...)

silver magnet
#

I'm using send() already

#

I'll try it

#

it's saved, now what can I write to make it add the reaction?

cold sonnet
#

await message.add_reaction(...)

silver magnet
#

do i use the raw emote or ::, and do i make it a string?

cold sonnet
#

is it an emoji in your server? or is it a basic emoji?

silver magnet
#

basic

final iron
cold sonnet
#

we do not understand you

silver magnet
polar ice
#

is there a way to add to a message?

Similar to edititing it but i want to keep the original message before it?

silver magnet
#

my memory sucks

final iron
#

Can I see your current code?

silver magnet
#
async def poll(ctx, *, message=None):
    if ctx.channel.id == 821116917753839627:
        if message is None:
            mes = await ctx.send("Argument error")
            return
        else:
            mes2 = await ctx.send(f"<@&821111383939743754>, `{message}`")
            await message.add_reaction(":thumbsup:")```
polar ice
#
@client.command()
async def poll(ctx, *, message=None):
    if ctx.channel.id == 821116917753839627:
        if message is None:
            mes = await ctx.send("Argument error")
            return
        else:
            mes = await ctx.send(f"<@&821111383939743754>, `{message}`")
            await mes.add_reaction(":thumbsup:")```

try?
silver magnet
#

still doesnt work :|

#

it sends the message

#

but no reactions

slate swan
#

is it possible to get the custom user banner in a guild (the one we can edit in every single guild through server profile if we have the 10$ nitro)
Because i sent a http request but could only get the custom server avatar

cold sonnet
#

๐Ÿ‘

#

copy this

#

await mes.add_reaction("๐Ÿ‘")

#

wait no

#

remove the else

#

and deindent the last two lines

#

your logic is kinda illogical

silver magnet
#

i just suck

#

it worked lol

polar ice
#

Also you could do

    if ctx.channel.id == 821116917753839627 and message is not None:```
potent spear
cold sonnet
#

it work

#

I use

#

modeeasy
memory spared
code readable

#

what the

#

how did I put a hecking book there

final iron
fast musk
#

hello]

sacred sigil
#

There are steps but I need some help

#

I can list them and you can help me

#

I use PyCharm btw

slim ibex
#

host on a vps

sacred sigil
#

such as?

slim ibex
#

vultr

sacred sigil
#

I need a free trial atm

#

The first step is add your SSH key

#

What is that? I've never used one to run my bot on PyCharm

slim ibex
#

SSH is secure shell

sacred sigil
#

how do I get it?

slim ibex
#

you can use PuTTY

pliant gulch
#

PuTTY isn't really needed anymore, windows has an ssh command iirc?

#

Same for linux

slim ibex
#

ohg yea in windows terminal

#

or in powershell/cmd

honest vessel
#
@commands.Cog.listener("on_message_delete")
    async def on_message_delete(self, message)
``` anyway to see if message was from a command being executed or simple message
#

that has been deleted*

#

\n newline add text

#

like py new_message "I wanna add this!" new_content = message.content+"\n"+new_message

summer lynx
#

how do i make so when you invite a bot it sends a welcome message saying like "thanks for inviting"

honest vessel
#

join messages?

#

event on_member_join()

severe rampart
#

!d discord.on_member_join @summer lynx

unkempt canyonBOT
#

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

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

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

await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Returns the invocation context from the message.

This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
pliant gulch
#

!d discord.ext.commands.Context.valid

unkempt canyonBOT
summer lynx
#

how do i set it up?

severe rampart
#
@client.event
async def on_memeber_join(member):
  # do stuff
#

@summer lynx

summer lynx
severe rampart
#

oh..

#

look thru discord.py api ref for an event that happens when the bot joins

velvet tinsel
#

client bad ๐Ÿ’€

#

and also itโ€™s member pithink

severe rampart
#

not when a member joins

velvet tinsel
#

you spelt member as memeber ๐Ÿ’€

severe rampart
#

did i

velvet tinsel
#

and bot is better

severe rampart
#

lol

severe rampart
velvet tinsel
#

ok

slate swan
#

Is it possible to use a file for an embed thumbnail instead of a url?
This doesn't work

ban_embed.set_thumbnail(file="./img/ban_hammer.png")
silent portal
#

@slate swan

filename = bla.png
file = discord.File(filename)

embed.set_thumbnail(url=f"attachment://{filename}")
await ctx.send(embed=embed, file=file)```
polar ice
#
if server_channel_admin_logs_message_id == 0:
  channel = client.get_channel(server_channel_admin_logs)
  await channel.send(f'``fix\nAdministrator: {admin} - {date} - {time}\n{command}``')
else:
  channel = client.get_channel(server_channel_admin_logs)
  msg = await channel.fetch_message(server_channel_admin_logs_message_id)
  await msg.edit(content=f"``fix\n{msg}\nAdministrator: {admin} - {date} - {time}\n{command}``")

Anyone know why this isnt working? im getting no errors

slate swan
potent spear
potent spear
polar ice
#

@potent spear Im trying to edit the message already in the channel and update it with a new line.

Nothing is actually happening ๐Ÿ™‚

potent spear
polar ice
#

@potent spearYes ive put prints in there

#

cant think of anything else to try?

potent spear
polar ice
#

No ๐Ÿ˜ฆ

potent spear
#

show me your whole command

polar ice
#

sure 2 secs

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

potent spear
#

this is a function you run in a command?

#

because that doesn't seem like a command to me

polar ice
#

@potent spear Yeah i run it from a command for now just for testing. once its working it will go on a loop

potent spear
#

you're also hiding stuff from me

#

you put all the stuff in a try block, but where did you except it?

livid carbon
#

I've been away from discord.py awhile, what fork should I goto that supports the newest features of discord and is most stable??

polar ice
potent spear
#

alright, remove the try catch and the errors will present themselves

polar ice
#

okay 2 secs ๐Ÿ™‚

#

@potent spear still no errors

#

the channel_id and the msg_id i store in a SQL Database as ints? would this be affecting it anyway?

potent spear
#

that's how it should be

polar ice
#

ahh good ๐Ÿ™‚

potent spear
#

make sure when you fetch them, they actually get returned as integers too

polar ice
#

let me print them just in case

potent spear
#

the types, not the values

polar ice
#

yeah

frank tartan
#

@client.command()
async def toggleDM(ctx, status):
    user_id = ctx.author.id
    if status == "enable":
        noDM_list.remove(user_id)
        await ctx.reply("You can now recieve dm's from me.")
    elif status == "disable":
        noDM_list.append(user_id)
        await ctx.reply("You can no longer recieve dm's from me.")
    else:
        await ctx.reply("Please put either `disable` or `enable`")

@client.command()
async def dm(ctx, user:discord.Member,*,message=None):
    user_id = ctx.author.id
    if user in noDM_list:
        await ctx.reply("That user has diabled the ability for me to send them a dm. Send it yourself.")
        return
    else:
        await user.send(f"{message}\n\nSent by <@{user_id}>")
        await ctx.send("DM sent.")

this is my code. when you run toggleDM disable, it adds your user id to the list, but it doesnt block ppl from dm @you message

how can i fix this
PLEASE I BEG YOU, PING IF YOU ARE RESPONDING TO ME OR I MIGHT ASK AGAIN

polar ice
#

@potent spear Yeah theyre definitly Ints

potent spear
slim ibex
polar ice
#

@potent spear ill try that now

slim ibex
#

what does it do

frank tartan
potent spear
#

I highly recommend using a botvar for this

frank tartan
#

then toggleDM enable removes your user id from the list, then it lets ppl dm you using hte bot

potent spear
slim ibex
polar ice
#

@potent spear still no errors

weary mirage
#

hello, can I get the username of a discord user who invokes?

potent spear
potent spear
weary mirage
#

ah, thank you :D

slim ibex
#

in your case, context.author.display_name

frail notch
#

Heya, how can I make a checker in my bot which checks if the inputted token, client ID, etc... is valid?

slate swan
#

I have this ticket system and it works for the most part but when i react to a ticket it gives me this error and it doesnt make a new channel called ticket 1
this is the full file https://mystb.in/HideAvonCrm.python

#

And this is what happened when I reran the bot

frail notch
weary mirage
#

this just gives me a long string of number D:

potent spear
frail notch
frank tartan
potent spear
weary mirage
#

is it possible to get the name and not the id?

frail notch
# potent spear that's not really dpy related

No... its not... ur right actually... the only reason i sent it here is cuz its part of a discord bot code.
Pretty much any user can add it to their server and get it to work in their serv by downloadin the code and inputting those

slate swan
potent spear
frail notch
potent spear
frail notch
frail notch
#

oh alr

polar ice
#

@potent spear So ive just done some more testing this is whats happened.

<Message id=929842242200408194 channel=<TextChannel id=929841976495456278 name='adminlogs' position=15 nsfw=False news=False category_id=929017222473592884> type=<MessageType.default: 0> author=<Member id=918225442480201818 name='Scum Bot' discriminator='8076' bot=True nick=None guild=<Guild id=847327487058247712 name="Poochington's server" shard_id=None chunked=True member_count=6>> flags=<MessageFlags value=0>>
Administrator: Screech - 2022.01.07 - 21.42.17
Command: 'listplayers'```

and then the last 2 lines change, instead of adding a new line.
potent spear
#

I can't help you without any code

frank tartan
potent spear
polar ice
#
channel = client.get_channel(server_channel_admin_logs)

msg = await channel.fetch_message(server_channel_admin_logs_message_id)
await msg.edit(content=f"``fix\n{msg}\nAdministrator: {admin} - {date} - {time}\n{command}``")```
frank tartan
potent spear
frank tartan
#

ok

potent spear
#

that way, you can always get the list

frank tartan
#

bot.noDM_list = []

potent spear
#

yes

frank tartan
#

ok

potent spear
#

that's what comes right under where you defined your bot

#

then you can easily access that botvar through any command

frank tartan
potent spear
#

ofc

frank tartan
#

cuz i use client instead of bot

potent spear
#

bot, client, shit, those are all variable names for the same object

frank tartan
#

kk

frank tartan
potent spear
#

I need to see some code

#

I'll rewrite it for you, that'll save you A LOT of time

frank tartan
#
@client.command()
async def toggleDM(ctx, status):
    user_id = ctx.author.id
    if status == "enable":
        client.noDM_list.remove(user_id)
        await ctx.reply("You can now recieve dm's from me.")
    elif status == "disable":
        client.noDM_list.append(user_id)
        await ctx.reply("You can no longer recieve dm's from me.")
    else:
        await ctx.reply("Please put either `disable` or `enable`")

@client.command()
async def dm(ctx, user:discord.Member,*,message=None):
    user_id = ctx.author.id
    if user in client.noDM_list:
        await ctx.reply("That user has diabled the ability for me to send them a dm. Send it yourself.")
        return
    else:
        await user.send(f"{message}\n\nSent by <@{user_id}>")
        await ctx.send("DM sent.")
    
@client.command()
async def noDmList(ctx):
    await ctx.reply(f"""{noDM_list}""")

ok

potent spear
#
@client.command()
async def toggleDM(ctx, status):
    author_id = ctx.author.id
    if status == "enable":
        client.noDM_list.remove(author_id)
        await ctx.reply("You can now recieve dm's from me.")
    elif status == "disable":
        client.noDM_list.append(author_id)
        await ctx.reply("You can no longer recieve dm's from me.")
    else:
        await ctx.reply("Please put either `disable` or `enable`")

@client.command()
async def dm(ctx, member: discord.Member, *, message=None):
    # I told you to change this if statement half an hour ago
    if member.id in client.noDM_list:
        await ctx.reply("That user has disabled the ability for me to send them a dm. Send it yourself.")
        return

    await member.send(f"{message}\n\nSent by {ctx.author.mention}")
    await ctx.send("DM sent.")
    
@client.command()
async def noDmList(ctx):
    await ctx.reply(f"""{client.noDM_list}""")```
#

yes, all the indentation is correct

frank tartan
potent spear
#

I fixed a lot of variable names too, you were confusing yourself with it

frank tartan
potent spear
#

doesn't matter, everything should work now

frank tartan
potent spear
weary mirage
#

oof okay I'm asking a lot of questions :P
How can I get my discord bot to wait for a reaction to then execute another bit of code

potent spear
weary mirage
#

could you link that perhaps, because I can't find that

potent spear
#

what have you tried? to find it

final iron
#

!d discord.Client.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). 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.9)") 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.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
final iron
#

Docs for wait_for

frail notch
#

How can I make it so that the user can input a list separated by commas and once inputted, the code will repeat add_to_guild with each id seperately?

[...]
userid = input("UserID> ")

[...]
def add_to_guild(access_token, guild_id, userid):
        url = f"{API_ENDPOINT}/guilds/{guild_id}/members/{userid}"

        data = {
        "access_token" : access_token,
    }
        headers = {
        "Authorization" : f"Bot {botToken}",
        'Content-Type': 'application/json'

    }
        response = requests.put(url=url, headers=headers, json=data)
        print(response.text)


code = exchange_code(excode)['access_token']

[...]
add_to_guild(code, get_guild_id, userid)```
final iron
#

uhm

#

Any reason you're not using a wrapper?

frail notch
#

wdym

slate swan
#

a wrapper is a library that simplifies the connection between the web services and local code

frail notch
#

i mean how much would it simplify it?

final iron
#

A lot

frail notch
#

like what would that chunk of code turn into

slate swan
#

well you should probably look into nextcord and find that out yourself

dire folio
#

how do i randomly add invisible characters to a string

final iron
#

@frail notch oh, you're creating a self bot

frail notch
#

its not...

#

bruh can i not just ask a question about a bit of code

final iron
#

But you were trying to get help about creating a self bot only 2 days ago, correct?

frail notch
#

dm me ill show u the full code

final iron
#

I'm not interested

frail notch
dire folio
#

how would i delete a message if it contains a specific word

final iron
frail notch
final iron
dire folio
#

ye

slate swan
#

await message.content.delete()?

final iron
#

await message.delete()

dire folio
#

i mean like say it contained the word fuck how would i delete it

final iron
#
if "word" in message.content:
    # delete
dire folio
#

that makes so much sense i don't understand why i didn't think of that

final iron
tiny ibex
#

.bm

dire folio
#

yes but for some reason it just did not come to my head

slate swan
#

I still dont know how to get those numbers like <t:197482927:f>

#

<t:197482927:f>

#

<t:197482927:R>

#

It's a timestamp

#

!e
import time

print(int(time.time()))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

1641764974
dire folio
#

how do i check if a user has a specific role in an on_message event

slate swan
#

<t:1641764974> - <t:1641764974>

slate swan
manic wing
#

<t:1641764974>

#

how do you

#

30 seconds ago

#

or whatever it is

slate swan
#

:R

manic wing
#

<R:1641764974>

#

:R:

slate swan
#

How you check it's up to you.
โ€ข Using a for loop
โ€ข Using discord.utils.get()
โ€ข Using if x in list

#

<t:1641764974:R>

#

:R, not R:

#

<t:1641764974:R>

dire folio
#

would the list contain the ids of the roles or the names?

slate swan
#

The role objects.

#

!d discord.Role

unkempt canyonBOT
#

class discord.Role```
Represents a Discord role in a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild")...
slate swan
#

A list of these objects.

#

You can still do something like

for x in y:
    print(f"{x.name} / {x.id}") # Will print role name / role ID
strong vessel
#

is there a way to make discord bot where when you type to it directly it will answer, without needing the commands like !bot

#

like where you dm the bot with text without commands

#

right now i only know how to import bot to servers, but is there a way to just have a bot that you share directly and people dm even when they don't own a server?

#

right now afaik the only way to get a discord bot from someone is either you have the share link, you own/admin a server and you import it there and then dm it, or you see the discord bot in someone else's server, is there a way to skip that step?

slate swan
#

I mean you could just set every letter as a command prefix? That could end poorly however

final iron
slate swan
#

Also I need inspiration for my bot

#

Cus im outta ideas

#

Honestly

strong vessel
#

is there a way to make discord bot where when you type to it directly it will answer, without needing the commands like !bot

slate swan
#

Yeah there is

#

Might be hard tho

#

It seems possible

strong vessel
#

the TeXit bot seems to do it

#

there is no bot prompt just dump text to it

#

through dm

manic wing
#

<:R1641764974>

#

:R:

strong vessel
#

i don't get it

manic wing
#

<1641764974:R>

final iron
#

<t:1641764974:R> <t:1641764974:R>

strong vessel
#

<t:1641764974:R>

manic wing
#

oh shoot im blind

final iron
final iron
cloud dawn
#

<t:9991766184:R>

final iron
#

<t:12368712387:R>

#

It would be nice if discord showed a preview of what it looks like before you send it

cloud dawn
#

<t:-2:r>

#

lmao

#

I guess

strong vessel
final iron
strong vessel
#

oh nvm

cloud dawn
#

How does one DM himself?

strong vessel
#

sorry i didn't realize it's impossible

final iron
#

Can you make a group and kick the other person from it making it empty?

#

That would be close to dming yourself

cloud dawn
final iron
#

A custom tag command is surprisingly easy

strong vessel
#

possible to make a server then dm it

final iron
#

How do bots create custom commands though?

#

Do they just use an on_message and filter from there?

velvet tinsel
#

custom...commands?

cloud dawn
velvet tinsel
#

I....what?

#

oh

final iron
velvet tinsel
#

I get what you mean

cloud dawn
#

custom commands would be more difficult with slash though

velvet tinsel
#

uh...on message I guess

nvm you mentioned it

#

MEE6 has some

idk if you can add arguments to your custom command though :pepegigascared:

cloud dawn
#

nah mee6 has only messages etc and some build in things

velvet tinsel
#

yeah

#

maybe...uhhh

#

wait, how do you get arguments from an on_message?

cloud dawn
#

With slash args would be more plausible.

final iron
#

Premium version of Gaius also has custom commands

green bluff
velvet tinsel
green bluff
#

pip freeze doesnt work

velvet tinsel
velvet tinsel
#

I guess you can add custom args

final iron
celest zinc
#

how do you count how many members are in your server

velvet tinsel
#

to a custom command

velvet tinsel
cloud dawn
velvet tinsel
#

I'm braindead

#

I should get sleep

celest zinc
final iron
unkempt canyonBOT
#

property member_count: int```
Returns the true member count regardless of it being loaded fully or not.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
velvet tinsel
celest zinc
#

o

velvet tinsel
#

but with custom commands I guess

final iron
#

intellisense is a god send

cloud dawn
final iron
#

I don't have to read docs anymore

#

Time for custom commands

green bluff
#

can anybody help ,e

#

pip is not recongnised

velvet tinsel
#
@bot.listen()
async def on_message(message):
  if message == "!foo"
    args = []
    for word in message.split()
      args.append(word)
      # extract stuff from json file ig?
      with open("commands.json", "r") as f:
        loaded = json.load(f)
        # shit
    # stuff
green bluff
#

in command prompt

velvet tinsel
#

bro

#

that's a general question

cloud dawn
velvet tinsel
#

panda confirm pls ๐Ÿ˜ณ

green bluff
celest zinc
velvet tinsel
cloud dawn
celest zinc
cloud dawn
strong vessel
#

any ideas of stuff without command

@bot.listen()
async def on_message(message):
  return message
#

would this work?

cloud dawn
final iron
#

That what im about to do

strong vessel
#

i'm trying to do without command

final iron
#

Custom commands are done with a on_message

strong vessel
#

like for DM the bot since no need command

strong vessel
#

but i've seen bots do weird things like TeXit seems to be able to just instantly do stuff without command (but it parses every message to see if it has $)

#

TeXit somehow solves this?

final iron
#

Maybe I just wont add arguments to the custom commands

strong vessel
#

ok i'll try idk

celest zinc
final iron
#

Should I allow a permissions restriction?

cloud dawn
final iron
#

Honestly learning sql was the best decision of my programming life

#

I literally learnt it in like 2 days

cloud dawn
cloud dawn
strong vessel
#

!pypi pandas

unkempt canyonBOT
#

Powerful data structures for data analysis, time series, and statistics

strong vessel
#

sql+pandas=legend

cloud dawn
slate swan
#

help me pls, i need an command to send two embeds, HOOW

celest zinc
cloud dawn
slate swan
#

@cloud dawn one embed only

#

i tried a thousand ways

#

and i cant

cloud dawn
slate swan
#

It does not work

cloud dawn
#

Code?

slate swan
#

i tried

#

or me who cant do

cloud dawn
#

No i'm asking to see your code.

slate swan
#

@cloud dawn bro, i tried again and worked

#

i love you, ty โค๏ธ

#

magic panda

cloud dawn
#

I haven't done anything ๐Ÿ˜…
But my presence can be quite special

feral lantern
#

what is the most efficient way to keep a bot written in python online 24/7?

feral lantern
#

thanks and how do i avoid my commands from putting the bot offline

final iron
feral lantern
#

they're repeating commands consistently every minute and it crashes the bot eventually

#

im hosting the bot locally not sure if that's the issue

final iron
#

When it crashes do you get any error or does the process just stop?

weary mirage
#

How can I ping the author in my ctx.send statement?

final iron
#

ctx.author.mention

weary mirage
#

thank you

velvet tinsel
#

thank you

final iron
#

No, thank you

potent spear
feral lantern
#

i never receive any errors and my wifi has an amazing uptime so it's definitely not that

feral lantern
potent spear
#

worth it

frail notch
#

How can I make it so that the user can input a list separated by commas and once inputted, the code will repeat add_to_guild with each id seperately?

[...]
userid = input("UserID> ")

[...]
def add_to_guild(access_token, guild_id, userid):
        url = f"{API_ENDPOINT}/guilds/{guild_id}/members/{userid}"

        data = {
        "access_token" : access_token,
    }
        headers = {
        "Authorization" : f"Bot {botToken}",
        'Content-Type': 'application/json'

    }
        response = requests.put(url=url, headers=headers, json=data)
        print(response.text)


code = exchange_code(excode)['access_token']

[...]
add_to_guild(code, get_guild_id, userid)```
final iron
#

Just want to confirm, getting the content of a message returns the content with all the markdown correct?

frail notch
feral lantern
#

reading the content of a text file then for each line you check them using the code you sent above

#

if you pasted all those guild ids it would be multiple inputs

final iron
cloud dawn
frail notch
#

Thats what Water_Gazes said 2 xD

frail notch
#

do u have any idea if thats possible?

cloud dawn
final iron
cloud dawn
frail notch
cloud dawn
#

Use f-strings please aaaa

frail notch
#

how do u expect me to write a library or whatever on my own xD

final iron
#

With a lot of help

frail notch
cloud dawn
#

And people create libraries with a lot of other people.

frail notch
slate swan
unkempt canyonBOT
#

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

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

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

cloud dawn
#

And as of now there is not one perfect Discord wrapper.

frail notch
#

ยฏ_(ใƒ„)_/ยฏ

slate swan
#

๐Ÿงโ€โ™‚๏ธ

cloud dawn
#

pff way too much coding lool

frail notch
#

oki doki

cloud dawn
#

Yes Andy i'm also too lazy ๐Ÿ˜‚

pliant gulch
pliant gulch
#

Don't

cloud dawn
#

Just bought a vps ๐Ÿฅณ

velvet tinsel
#

caeden's gonna kill me

#

he killed me 10 times today

cloud dawn
#

Just insult him and you're good

weary mirage
#

okay so I have this
def check(reaction, user): return str(reaction.emoji) == ':thumbsup:' try: await bot.wait_for('reaction_add') except asyncio.TimeoutError: await channel.send(':thumbsdown:') else: channel = bot.get_channel(929823408684953642) await channel.send(ctx.author.mention + "Your order has been confirmed.")

#

but when I react with any emoji, it still works, can I get it so I need to react with the โœ… emoji?

cloud dawn
#

What even is happening here

#

Why is the wait_for in the check?

weary mirage
#

I... don't know D;

#

I'm trying to get a basic order confirmation thing, when someone types !order, and it'll send what was ordered to another private chat
then the person (shop keeper) can reply with a โœ… or โŒ to either confirm the order or deny it

#

I uh... must've fucked up something along the way ๐Ÿค”

#

how can I go along fixing this mess o.o;

#

okay so I was using code from the docs
do I just use await bot.wait_for like this here?

async def order(ctx,*,message):
    await ctx.send("please wait for Becka to confirm your order.")
    channel = bot.get_channel(929837471469015090)
    await channel.send(str(ctx.author.name) + " ordered " + message)
    await bot.wait_for('reaction_add')```
frail notch
#

When using try except how can i make it so that it checks if botToken = over 20 characters long ?

frail notch
final iron
#

You don't. Use an if statement

#

The point of using a try except block is to catch errors and deal with them

frail notch
#

ooh

#

so like

#
if len < 20 
  print("Invalid")
else
  print("Valid")
```?
final iron
#

Its a function

velvet tinsel
#

where is the :

final iron
#

Also that

weary mirage
#

how can I use bot_for for confirmation D:

final iron
weary mirage
#

I've been reading the docs, that's what I've been using as reference but it didn't work

weary mirage
#
async def order(ctx,*,message):
    await ctx.send("please wait for Becka to confirm your order.")
    channel = bot.get_channel(929837471469015090)
    await channel.send(str(ctx.author.name) + " ordered " + message)
    def check(reaction, user):
        bot.wait_for('reaction_add')```
#

is what I have rewritten rn

#

When somebody uses !order, it'll take the message and send it to another chat where the person in charge of the shop (because thats what its being used for) can use the โœ… reaction to confirm the order

slate swan
#

Which wrapper library are you running and which version?

#

@weary mirage

weary mirage
#

I'm new to programming, whats that?

frail notch
#

Would there be a way for me to check the ID of all users who authorised my bot's app (in their authorised apps)?

slate swan
weary mirage
#

it should be rather recent, I think

elfin smelt
#

who wants to make discord bots

weary mirage
#

how can I check it

elfin smelt
#

like collab

slate swan
#

Looks to be a discord.py fork, if you installed it with pip it should be the latest version

#

my point is, pass_context has been deprecated a long time ago, and is no longer required

#

you may remove it from the order function definition line

#

as for your initial question;

elfin smelt
weary mirage
#

I used that from something I found that on stack overflow

slate swan
#

wait_for expects you to give it a check function,

slate swan
weary mirage
#

alright

slate swan
#

do you follow so far?

weary mirage
#

uh I lost you at "just added equals the person in charge of the shop"

slate swan
#

You want to make it so only whoever is in charge of the shop can confirm an order by clicking the reaction, yes?

weary mirage
#

yes

slate swan
#

Then, when any reaction is added to the message, your code has to check if whoever added that reaction is the shop's owner.

weary mirage
#

but I want it to be so they have to react to the message sent to their chat specifically for that

weary mirage
slate swan
#

Ah, I see that command is supposed to only run in a DM, right?

#

but a different message is sent to a specific channel that the shop's owner can see

weary mirage
#

yes

slate swan
#

and they'll react there

weary mirage
#

indeed

slate swan
#

okay, that ever so slightly complicates things

weary mirage
#

instead of a dm though, its a "checkout" chat

#

on the same server

#

that's just how they wanted it D:

slate swan
#

I see

#

alright, you know how you can store variables in python

weary mirage
#

uh, ig

slate swan
#

You may store details for a message that has not yet been sent, i'll explain

#

If you write

message = await ctx.send('Hello!')
#

You may later on, (in the same command) reference something such as message.id

#

as long as the message was sent without an error

weary mirage
#

okay ๐Ÿค”

slate swan
#

So, when a user adds a reaction our check function has to check for the following:

#
  1. This message that this reaction was added to, Is it the correct message in the correct channel?
  2. This user that reacted, is this the shop's owner?
#

Get it so far?

weary mirage
#

uh, I think so yes

slate swan
#

So here's what we are going to do first:

message = await channel.send(str(ctx.author.name) + " ordered " + message)```
#

As I explained earlier, this will save details regarding the specific message later on, so we can use it

weary mirage
#

okay :o

#
async def order(ctx,*,message):
    await ctx.send("please wait for Becka to confirm your order.")
    channel = bot.get_channel(929837471469015090)
    message = await channel.send(str(ctx.author.name) + " ordered " + message)
slate swan
#

Since I haven't practiced discord.py for a while, i'm going to spin up a test bot just to ensure i'm not saying something wrong. Please hold

weary mirage
#

alright :o

slate swan
#

Sorry for the wait, i just finished doing the above

#

had to set up a server and everything lol

weary mirage
#

oof

slate swan
#

alright, just quickly testing if this code works, just a bit more

#

@weary mirage you still there, little man?

weary mirage
#

yes :D

slate swan
#

alright, let's go over the following code together

#
@bot.command()
async def order(ctx,*,message):
    await ctx.send("please wait for Becka to confirm your order.")
    channel = bot.get_channel(929892204347015178)
    user_id = 847834751230148618
    message = await channel.send(str(ctx.author.name) + " ordered " + message)
    await message.add_reaction("โœ…")
    #wait for the user to react, check if the user reacted with the correct emoji, check if the users id equals user_id and check if its the right message
    def check(reaction, user):
        return user.id == user_id and str(reaction.emoji) == "โœ…" and reaction.message.id == message.id

    try:
        reaction = await bot.wait_for('reaction_add', check=check)
    except Exception as e:    
        await ctx.send("Order failed, please try again.")                
    else:
        await ctx.send("Your order has been placed.")                                                    
        await channel.send("Order confirmed.")   
#

first, remember to replace the channel ID in the channel = line

#

same thing for the user_id line, replace that with becka's user ID

weary mirage
#

um okay

patent lark
#

thats some poorly written code.

slate swan
patent lark
#

it doesnt follow pep8, and, why are you catching the exception as e if you arent doing anything with it?

slate swan
#

regardless, the check function i did checks for the criteria we previously went through, including checking if the added reaction is the proper one.. which I forgot to mention we should do

weary mirage
#

:o

slate swan
#

anyway, the check function checks if the user.id of who reacted equals the user_id variable, it checks if it is the correct message and the correct emoji as well

#

then we have a try block for convenience, and the wait_for line

#

add raise e

#

below the order failed line

patent lark
#

also

#

something else

weary mirage
#

I got this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'

slate swan
weary mirage
#

ooh maybe

patent lark
weary mirage
#

ooh alright

#

it works :D

slate swan
#

and you understand how the code functions?

weary mirage
#

yus :D

slate swan
#

in case the bot goes down while an order is awaiting confirmation

#

i must make it clear that when the bot goes up again it will not confirm

#

because of the way wait_for works it isn't persistent between bot restarts

#

you would need to go through some more code to make that work

#

should be fine as long as it doesn't go down too often

weary mirage
#

ah I expected that, though that shouldn't be much of an issue at all

slate swan
#

in case it does go down it'll send a "order failed" message

#

the thing snow talked about earlier, pep8

#

is a list of rules your code is supposed to follow, a style guide we call it

patent lark
#

!pep8

unkempt canyonBOT
#

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
โ€ข PEP 8 document
โ€ข Our PEP 8 song! :notes:

slate swan
#

you don't need to follow pep8, but it is reccomended for convenience

#

and ease of readability for code

weary mirage
#

would it be possible to have it so it can accept both โœ… for confirmation and โŒ for order denial?

patent lark
#

yes

weary mirage
slate swan
#

yeah, you just need to tweak it a little

#

snow can help you with that

weary mirage
#

thank you for your help, you've been most kind :D

patent lark
#

wrench, are there no cases where you think raising a timeout would be necessary?

slate swan
#

owner may be offline when a user attempts to order something

weary mirage
#

yes, so the shop owner is European in a mostly American server so it's not unlikely for time zones to get in the way there

slate swan
#

alright that's about all I can offer now,

weary mirage
#

thank you! :D

slate swan
#

happy coding!

weary mirage
#

I'll try o.o

#

kek

robust ridge
#
@client.command()
async def fga(ctx):
     members = ctx.guild.members
     for member in members:
            print(member)
#

local variable 'guild' referenced before assignment

#

guild aint defined idk why

feral lantern
weary mirage
#

b4u?

feral lantern
#

buy for you

#

a food service

weary mirage
#

uh no?

barren fog
cloud dawn
barren fog
#

l

soft lynx
#

Is there a way to restrict the roles that pop up when using option 8? Option 8 makes all roles show up - i could assign choices to the option but it would take a really long time, because i want to include a long list of roles .

slate swan
#

guys

#

can someone help me with a thing

soft lynx
slate swan
#

So

#

I want to make a bot

#

but i am tryna figure out the message

#

part

#

like if you say ;hunt

soft lynx
#

i dont exactly understand your question

slate swan
#

then the bot will reply

slate swan
soft lynx
#

you should probably read the documentation

#

what is your current code?

slate swan
#

a command is just a function

slate swan
soft lynx
#

thats the old way of doing things

slate swan
#

and use f strings

#

!f-strings

unkempt canyonBOT
#

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

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

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

slate swan
#

!indents

unkempt canyonBOT
#

Indentation

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

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

Example

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

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

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

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

soft lynx
slate swan
#

yes ik

#

The bot will say someone caught a rabbit

#

good tutorial which might help you

#

I'm using pycharm

slate swan
slate swan
#

your indentations are wrong

#

nice

slate swan
potent spear
# soft lynx anyone?

you're leaving a lot of data for us to figure out
like what you have
what you're trying to do,...

slate swan
soft lynx
cloud dawn
#

!source pypi

unkempt canyonBOT
#
Command: pypi

Provide information about a specific package from PyPI.

Source Code
potent spear