#discord-bots

1 messages · Page 861 of 1

final iron
#

No it's not

#

Take a picture of the console

stiff nexus
#

bruh

slate swan
#

Ok nvm its fixed thanks u, im proud of u sasuke

#

Thats my little brother..

slim ibex
#

What does the linter say when it complains about defaulting to Nond

kindred epoch
#

yes

cold sonnet
#

!d discord.TextChannel.permissions_for

unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
cold sonnet
#

pass in your member

#

get permissions

#

check for permissions

#

change outcome

kindred epoch
cold sonnet
#

well yes

#

!d discord.Guild probably has that too

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a “server” in the official Discord UI.

x == y Checks if two guilds are equal.

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

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
kindred epoch
#

nah it doesnt

#

well there is ctx.author.guild_permissions but it returns as permissions value

#

!d disnake.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://docs.disnake.dev/en/latest/api.html#disnake.abc.GuildChannel.permissions_for "disnake.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership and the administrator implication.
cold sonnet
#

looks something like
[(administrator, False), (connect, True)]

kindred epoch
#

idk why its doing that

native wedge
final iron
native wedge
cold sonnet
#

returns this

final iron
kindred epoch
# cold sonnet

ye you have to do ```py
ctx.author.guild_permissions.send_messages

cold sonnet
#

yes

#

👍

#

either my bus is too late or I was too deep in this convo

kindred epoch
spring flax
#

can anyone guide me on how to make a bot notify when a streamer goes live on, say, Youtube/twitch

tacit storm
honest vessel
#

check stream often and when its live send msg to discord and set a variable like live=1 and set it live=0 when its found offline again this helps prevent it spam when it checks stream that its live after each time it still live etc...

#

so bot will only alert if live=0 and stream is live

honest vessel
#

myself uses database and has a column live wich i set 1 or 0 and updates this depend if its online or offline and when it had 0 and puts 1 it sends to discord

tacit storm
#

^
it’s optional but it’s gonna be more helpful

honest vessel
#

i other hand has alot of streamers and uses dlive twitch youtube

spring flax
#

there's no module for this?

tacit storm
#

requests is blocking

#

if anything, use aiohttp.

it’s made for async projects

honest vessel
#

aiohttp

spring flax
#

i mean it'll have concerning ratelimits

#

bots do not have access to the search feature on discord for one

#

maybe it puts the message count in a db

tacit storm
#

im not sure the best way but you can look through the source of python bot to try to see what it does

spring flax
#

yeah python bot uses a database

tardy atlas
#
online = len(list(filter(lambda x: x.status == discord.Status.online, mbrs)))                        
        print(f"{online}")
        idle = len(list(filter(lambda x: x.status == discord.Status.idle, mbrs)))
        offline = len(list(filter(lambda x: x.status == discord.Status.offline, mbrs))) 
        dnd = len(list(filter(lambda x: x.status == discord.Status.dnd, mbrs)))  

Shows the wrong number of people on the server (by status)?

spring flax
#

intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

tardy atlas
#

@spring flax The team is in cogs, should I write intents there?

spring flax
#

yeah that's likely the best way though

spring flax
spring flax
#

and no i don't think it'd be that buggy

spring flax
tardy atlas
lyric tusk
#

is thear a way i can send a message in a chat when some add the bot like the guild id

kindred epoch
#

i mean big db's like postgres will be able to handle that with ease, and using it asynchronously should work fine

unkempt canyonBOT
#

disnake.on_guild_join(guild)```
Called when a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild") is either created by the [`Client`](https://docs.disnake.dev/en/latest/api.html#disnake.Client "disnake.Client") or when the [`Client`](https://docs.disnake.dev/en/latest/api.html#disnake.Client "disnake.Client") joins a guild.

This requires [`Intents.guilds`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.guilds "disnake.Intents.guilds") to be enabled.
lyric tusk
kindred epoch
#

🤷‍♂️ but maybe try making a whole new connection just for that if you think its slowing down

safe herald
#

whats the difference between bot.command and command.comm and?

tardy atlas
spring flax
stiff nexus
#

how do i do pagination in buttons?

kindred epoch
#

idk depends on what u are doing

lost lichen
#

how can i make it send a message if an emoji is reacted with? I cant put await inside of a check, and i cant async the check otherwise it doesnt read the emoji reaction...

lost lichen
kindred epoch
#

its just bot not ctx.bot so yes remove it, and the check function is really wrong, the check function is for checking if the reactions are from the list and the user is the author

#
@client.event
async def on_message(message):
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that 👍 reaction, mate')

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '👍'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('👎')
        else:
            await channel.send('👍')
``` look at this example
lost lichen
#

i have multiple emojis that i want to do different things based on which emoji was reacted with

kindred epoch
#

so you have to do something like this

def check(reaction, user):
    return user == ctx.author and str(reaction.emoji) in list_of_emojis
kindred epoch
#

instead of just making them in the check function

lost lichen
#

put the if statements inside of the try:?

kindred epoch
#

yes inside the try and under the wait_for

#
try:
    reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
    #if statements
slate swan
#

uh, how do I upload animated emojis catsip

pallid escarp
#

so this works when i say it but i want others to say it and it will also reply to them@bot.event async def on_message(ctx): if ctx.content == "Hello": await ctx.reply("Hey!")
why does it only listen to me?

slate swan
#

hi

lost lichen
slate swan
#

is there one? I dont think so

unkempt canyonBOT
#

disnake.on_invite_create(invite)```
Called when an [`Invite`](https://docs.disnake.dev/en/latest/api.html#disnake.Invite "disnake.Invite") is created. You must have the [`manage_channels`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_channels "disnake.Permissions.manage_channels") permission to receive this.

New in version 1.3.

Note

There is a rare possibility that the [`Invite.guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Invite.guild "disnake.Invite.guild") and [`Invite.channel`](https://docs.disnake.dev/en/latest/api.html#disnake.Invite.channel "disnake.Invite.channel") attributes will be of [`Object`](https://docs.disnake.dev/en/latest/api.html#disnake.Object "disnake.Object") rather than the respective models.

This requires [`Intents.invites`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.invites "disnake.Intents.invites") to be enabled.
slim ibex
#

I usually use the member id, xp, level, guild id, number of infractions, etc

slate swan
#

whaaa awkward

slim ibex
#

but for my new bot, I am handling infractions differently

slim ibex
#

I’m making a separate infractions table with all the information of an infraction that include infraction id, target id/name, issuer id/name, etc

#

I use a helper infractions file to handle all this stuff

lost lichen
slim ibex
#

and I’m my infraction class are methods to grab infraction, show expired infractions, etc

kindred epoch
pallid escarp
#

so this works when i say it but i want others to say it and it will also reply to them@bot.event async def on_message(ctx): if ctx.content == "Hello": await ctx.reply("Hey!")
why does it only listen to me?

kindred epoch
slate swan
slim ibex
#

I’m going to work on that one. I might just make the infraction id column auto increment

pallid escarp
# slim ibex on_message doesn’t take ctx

The Bot will only respond to me but i want it so it responds to other people @bot.event async def on_message(message): if message.content == "Hello": await message.channel.send("Hey!")

slim ibex
#

generating a long random number might be interesting when an infraction is created

slate swan
pallid escarp
#

@slim ibex see it works when i say Hello but if you were to say it it wouldnt work

safe herald
#

is it possible to make the bot say something every specific day?

slim ibex
#

I also use an enum to classify infraction severity

class InfractionType(Enum):
    NOTE = 0
    WARN = 1

@slate swan

safe herald
#

so every 25th of feb etc it says something?

lost lichen
slim ibex
boreal ravine
#
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'HelpCommandDropdown' object has no attribute 'ctx'
slim ibex
#

yeah enums are helpful

kindred epoch
slate swan
slim ibex
#

mind you, this bot I’m making is for a single server lmao

kindred epoch
slate swan
slim ibex
#

I might be overdoing it but, I can use these features if I ever make another bot I intend to distribute to multiple servers

lost lichen
honest shoal
#

how to purge messages of a specific user?

kindred epoch
lost lichen
boreal ravine
unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Examples

Deleting bot’s messages...
kindred epoch
lost lichen
honest shoal
kindred epoch
lost lichen
#

like i said before, the user in the try is not being used either...

#

ok let me try that

lost lichen
#

i will try removing the str()

#

yeah nothing, still doesnt go to the if statement after that

kindred epoch
#

hm

kindred epoch
lost lichen
#

(it doesnt print reached else either)

sick birch
#

You might have to str(reaction.emoji)

final iron
#

!d discord.Reaction.emoji

unkempt canyonBOT
lost lichen
#

let me try that again, i had done str(reaction.emoji) then removed it a few mins ago because it still wasnt working

final iron
#

Try what robin suggested

#

It won't always return a string

lost lichen
kindred epoch
red nest
#

you have to put the if str(reaction.emoji) outside of the try:

lost lichen
kindred epoch
#

wtf

pallid escarp
#

The Bot will only respond to me but i want it so it responds to other people @bot.event async def on_message(message): if message.content == "Hello": await message.channel.send("Hey!")

lost lichen
lost lichen
#

doesnt print anything

red nest
#

oh no sorry

#

i made an error i will correct it

#
        str(reaction.emoji) == 'your emoji'```
#

put that before the try

lost lichen
#

it is before the try..

red nest
#

then show the entire code please

lost lichen
red nest
lost lichen
kindred epoch
lost lichen
#

entire code

red nest
slate swan
#

Hello

#

I have a problem with command

#

He just not work

lost lichen
red nest
#

yeah

unkempt canyonBOT
#

Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

slate swan
#

Oh

lost lichen
#

dont post your discord bot token

red nest
#

you have to put three ` before and after the code

lost lichen
#

you should keep the token in a seperate file and read it btw

slate swan
#

import discord

client = discord.Client()

@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
if message.author == client.user:
return

if message.content.startswith('@alpine bobcat'):
    await message.channel.send('Hello! My prefix is +.Command list +help')

client.run('token')

#

On replit he worked

slate swan
red nest
#

ok...

slate swan
#

Bot just online

red nest
#

ok

#

so you should type @alpine bobcat

#

in the chat

#

so that your bot responds with it

lost lichen
#

yep, thats what your code is looking for

red nest
#

yes

slate swan
red nest
#

message.content.startswith checks if the message starts with it

red nest
#

try replacing @alpine bobcat with anything else to check if it works or not

lost lichen
#

i think what they are trying to do is if the bot gets mentioned, it replies with the prefix and help command, correct?

tacit token
#

Is it allowed to make a music bot?

red nest
red nest
tacit token
red nest
red nest
lost lichen
# slate swan Yes

import discord

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('Hi there!'):
        await message.channel.send('Hello! My prefix is +.Command list +help')

client.run('token')

with this if you type Hi there! it should respond, try doing that to make sure it responds

lost lichen
tawdry panther
#

Ahha thanks

red nest
slate swan
#

Ok i go to test this

#

Client Superman

#

imagine still using Client anime_shrug

red nest
#

everyone has a different opinion

lost lichen
#

does it work? yes it does, so its not "wrong" to use it...

slate swan
lost lichen
#

and?

slate swan
#

and doesnt support Commands

#

and cogs

kindred epoch
slate swan
red nest
lost lichen
red nest
red nest
#

oh

#

replit has discord.py by default, that's why it didn't work

slate swan
kindred epoch
#

what are you saying?

kindred epoch
# slate swan Error

theres an invisible character after that parenthesis that you need to remove

lost lichen
#

its a unicode character error, it detects a space after that

red nest
#

so just delete spaces until the )

lost lichen
#

yeah, on your client.run() there is a space after the closing bracket ) delete the space

lost lichen
#

try running again

slate swan
red nest
#

show your error please

slate swan
#

Bot turned on

slim ibex
#

mobile programmer 🦾

slate swan
#

But commands not work

red nest
#

are you getting a error message

slate swan
honest vessel
slate swan
red nest
red nest
slate swan
lost lichen
#

token is incorrect

red nest
#

that means that the token is not correct

honest vessel
lost lichen
slim ibex
#

What’s wrong?

lost lichen
#

it doesnt filter which reaction was reacted with

slim ibex
#

Show code

lost lichen
#

dpoesnt show anytrhing in terminal

slim ibex
#

ctx.bot.wait_for??

red nest
# lost lichen

so in my code the if str(reaction.emoji)is outside of the try

lost lichen
#

was told to test it like that lol, let me remove the ctx and try again

boreal ravine
# lost lichen

Do reaction, user = .... reaction is a tuple if you do it like that

slate swan
#

Thanks .

red nest
#

you need await bot.wait_for

lost lichen
#

still doesnt work after removing ctx

red nest
lost lichen
#

it just times out

lost lichen
#

where is reaction, user = i dont see it

torn sail
boreal ravine
lost lichen
slim ibex
#

he is saying to add it lmao

torn sail
lost lichen
#

its already adding the emojis

#

see here it shows 2 ppl reacted, one is the bot the other is me

slim ibex
boreal ravine
lost lichen
#

i know

#

my issue is not adding the reactions

#

my issue is running something when one of those emojis is reacted with by the user

#

in this case, a simple print()

boreal ravine
#

mate, you do realize that ```py
reaction = await bot.wait_for("reaction_add", ...)

slim ibex
#

^

boreal ravine
#

and you are using an "emoji" attribute on a tuple

slim ibex
#

^

slate swan
#

how to remove the delay in sending a command?

lost lichen
#

huh??

slim ibex
#

str(reaction.emoji)

red nest
slim ibex
#

the tuple has no attribute of emoji

lost lichen
green veldt
#

im getting html kind of error when im running my repl, is my bot rate limited?

slate swan
red nest
#

oh

boreal ravine
green veldt
lost lichen
red nest
#

you can't really make it faster

boreal ravine
cosmic agate
#

File "main.py", line 110
@bot.command()
^
IndentationError: unexpected unindent

red nest
#

sometimes

boreal ravine
slate swan
slim ibex
#

low bandwidth

cosmic agate
#

File "main.py", line 110
@bot.command()
^
IndentationError: unexpected unindent

help

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

boreal ravine
red nest
#

that should not be there

cosmic agate
#

there is none

pallid escarp
#

How do i change my discord py bot version? (i want to go from rewrite to previous versions)

red nest
#

maybe you forgot to close a parenthesis or something

lost lichen
#

since user was not being used or something

red nest
slim ibex
#

you need user if you want to access a user iirc

slate swan
#

Sad

red nest
lusty yew
#

Did someone try to make a bot what you can listen to a radio in a voice channel with?

boreal ravine
boreal ravine
cosmic agate
red nest
#

ok...

boreal ravine
red nest
lost lichen
red nest
cosmic agate
#

hmm

lost lichen
#

just times out

cosmic agate
boreal ravine
cosmic agate
#

for code view?

boreal ravine
#

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

red nest
#

oh

cosmic agate
#

thanks

#

@boreal ravine

red nest
cosmic agate
#

this is code

red nest
cosmic agate
red nest
cosmic agate
#

ok sir

red nest
red nest
#

because that's what i would say

cosmic agate
#

man im kinda dumb

red nest
#

why?

lost lichen
cosmic agate
boreal ravine
red nest
lost lichen
#

just this

#

AKA just the timed out

boreal ravine
cosmic agate
lost lichen
#

this is also running in a cog btw

cosmic agate
#

soo i might miss something

lost lichen
red nest
oblique adder
#

how do i check in on message if someone sent a mp3 file ?
and get its url ?

boreal ravine
cosmic agate
lost lichen
cosmic agate
#

js?

red nest
cosmic agate
boreal ravine
#

!d discord.Message.attachments message.attachments[0].url maybe

unkempt canyonBOT
boreal ravine
red nest
# lost lichen

the if str(reaction.emoji) needs to be outside of the try

cosmic agate
#

hmm

#

ill change position of command timerhelp

#

lemme check if that works ig

#

sed

#

no success

red nest
#

ok

cosmic agate
#

it blames the command under timerhelp

red nest
#

it should be like this

lost lichen
#

im going mental on this project

cosmic agate
#

mine too XD

cosmic agate
#

sed

red nest
cosmic agate
#

hmm

lost lichen
#

the fact my code was working perfectly before, i just couldnt send a message, and everyone here told me to change my whole check function FaceCrybaby

red nest
lost lichen
cosmic agate
#

lol what

lost lichen
#

this WAS my code before, my problem was i couldnt put await ctx.send, but it would print the colour based on the reaction pressed perfectly, lmao

oblique adder
#

does message.content return none if there is only files ?

buoyant igloo
nimble plume
#

Hi

red nest
lost lichen
#

so you see, when i had it setup like that screenshot, you cant put await inside of a check function, and you cant async the check function either bcecuase otherwise it just doesnt function

cosmic agate
#

File "main.py", line 111
@bot.command()
^
IndentationError: unexpected unindent

#

help anyone?

red sundial
#

unexpected unindent

red nest
cosmic agate
red sundial
#

errors don't lie

lost lichen
# red nest yeah

so... how would i have made it send the message and accept only 1 reaction?

lost lichen
cosmic agate
red nest
red nest
buoyant igloo
nimble plume
#

Im lagging

lost lichen
red nest
# lost lichen so... how would i have made it send the message and accept only 1 reaction?

something like this ``` valid_choices = ["🪨", "📰", "✂"]
ai_choices = ["Rock", "Paper", "Scissors"]
ai_choice = random.choice(ai_choices)
embed = discord.Embed(
title='Rock Paper Scissors',
description='React with the emojis to play',
color=discord.Colour.random()
)
embed.set_footer(text="Rock Paper Scissors Game")
msg = await ctx.send(embed=embed)
await msg.add_reaction("🪨")
await msg.add_reaction("📰")
await msg.add_reaction("✂")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in valid_choices
try:
reaction, user = await bot.wait_for('reaction_add', timeout = 30.0, check=check)
#i added that for debugging some code but i'm too lazy to delete that
print("reaction passed")
except asyncio.TimeoutError:
return await ctx.send("Not fast enough my guy!")
if str(reaction.emoji) == "✂":
if ai_choice == "Rock":
await ctx.send("HAHAHAHA! I SMASHED YOU WITH MY ROCK!")
elif ai_choice == "Scissors":
await ctx.send("Tie! No one wins! We both chose this red thing right here: ✂")
else:
await ctx.send("Nooooooooo... You got me with your scissors")
if str(reaction.emoji) == "🪨":
if ai_choice == "Paper":
await ctx.send("Yes! I packed your rock into paper!")
elif ai_choice == "Rock":
await ctx.send("Tie! No one wins! But why did we try to fight ourselves with the same thing?")
else:
await ctx.send("WHAT? HOW DID YOU JUST SMASH ME?")
sleep(0.1)
await ctx.send("aimbot")
sleep(0.1)
await ctx.send("hacker")

red nest
buoyant igloo
nimble plume
red sundial
#

so im trying to make a slowmode command. im using pycord, here's my code

@slash_command(guild_ids=[918349390995914792], description="slowmode")
    async def slowmode(ctx, seconds: int):
        await ctx.channel.edit(slowmode_delay=seconds)
        await ctx.send(f"Slowmode set to {seconds} seconds.")
``` this is inside a cog called `Fun` 

when i use it it raises an error
```Application Command raised an exception: TypeError: Fun.slowmode() got multiple values for argument 'seconds'``` any help would be appreciated
red nest
red sundial
red nest
#

yeah

south jetty
#
 line 3, in <module>
    from help_cog import help_cog
ImportError: cannot import name 'help_cog' from 'help_cog'```
Why isn't it importing
buoyant igloo
#

Idk man I don’t trust any link

red sundial
red nest
buoyant igloo
south jetty
red sundial
#

so idk why thats happening lol

slate swan
#

Is it possible to use json file as a list of sorts?

lost lichen
# red nest something like this ``` valid_choices = ["🪨", "📰", "✂"] ai_choices = ["...
    valid_choices = ["🪨", "📰", "✂"]
    ai_choices = ["Rock", "Paper", "Scissors"]
    ai_choice = random.choice(ai_choices)
    embed = discord.Embed(
        title='Rock Paper Scissors',
        description='React with the emojis to play',
        color=discord.Colour.random()
    )
    embed.set_footer(text="Rock Paper Scissors Game")
    msg = await ctx.send(embed=embed)
    await msg.add_reaction("🪨")
    await msg.add_reaction("📰")
    await msg.add_reaction("✂")
    def check(reaction, user):
        return user == ctx.author and str(reaction.emoji) in valid_choices
    try:
        reaction, user = await bot.wait_for('reaction_add', timeout = 30.0, check=check)
        #i added that for debugging some code but i'm too lazy to delete that
        print("reaction passed")
    except asyncio.TimeoutError:
        return await ctx.send("Not fast enough my guy!")
    if str(reaction.emoji) == "✂":
        if ai_choice == "Rock":
            await ctx.send("HAHAHAHA! I SMASHED YOU WITH MY ROCK!")
        elif ai_choice == "Scissors":
            await ctx.send("Tie! No one wins! We both chose this red thing right here: ✂")
        else:
            await ctx.send("Nooooooooo... You got me with your scissors")
    if str(reaction.emoji) == "🪨":
        if ai_choice == "Paper":
            await ctx.send("Yes! I packed your rock into paper!")
        elif ai_choice == "Rock":
            await ctx.send("Tie! No one wins! But why did we try to fight ourselves with the same thing?")
        else:
            await ctx.send("WHAT? HOW DID YOU JUST SMASH ME?")
            sleep(0.1)
            await ctx.send("*aimbot*")
            sleep(0.1)
            await ctx.send("*hacker*")

ignore its just so i can read it better

red nest
#

ok

#

wait a minute

buoyant igloo
#

“What? How did you smash me?” Sounds gpkinda sus man

lost lichen
red nest
slate swan
slate swan
unkempt canyonBOT
#

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

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

import discord

# Bunch of bot code

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

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

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

lost lichen
#

oh yeah, if you do sleep it will stop the rest of the code, thats why you have to async it

red nest
#
   def check(reaction, user):
       return user == ctx.author and str(reaction.emoji) in valid_choices
    try:
        reaction, user = await bot.wait_for('reaction_add', timeout = 30.0, check=check)
    except asyncio.TimeoutError:
        return await ctx.send("Not fast enough my guy!")
    if str(reaction.emoji) == "🪨":
      your code```
red sundial
slate swan
#

it will block all of your code and making your bot not acknowledge a heartbeat so it will get disconnected from the websocket and from the api

lost lichen
red nest
left crater
#

how do i send an image in an embed

lost lichen
slate swan
unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.

Changed in version 1.4: Passing [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") removes the image.
left crater
#

cuz this is what it is doing rn

lost lichen
#

exactly embed.set_image()

left crater
#

ok thanks

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() got an unexpected keyword argument 'timeout'
what should i do to fix this i am using discord.py

lost lichen
# left crater ok thanks
picture = <picture you want>
embed = discord.Embed(title=f'Picture:', colour=0x400080)
embed.set_image(url = picture)
await ctx.send(embed=embed)```
slate swan
south jetty
slate swan
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

load_extension(name, *, package=None)```
Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
lost lichen
slate swan
lost lichen
#

code should work regardless of who runs it

honest shoal
#

hi, is there any way to set multiple images in embed? I have seen recently that link embeds are having multiple images is it possible through bot?

slate swan
tacit storm
lost lichen
red nest
#

idk

tacit storm
red nest
tacit storm
lost lichen
# red nest maybe

but that shouldnt affect it lmao, ugh why doesnt it wanna workkk :(

lost lichen
#

response time is not discord bot api response time btw

cosmic agate
#

@red nest i removed count command and now it works

red nest
#

ok

#

so the error was in the count command

lost lichen
slate swan
tacit storm
slate swan
slate swan
lost lichen
slate swan
#

main does have buttons but doesn't have other new features like timeout

tacit storm
#

alr

slate swan
lost lichen
#

what do you mean

slate swan
#

in your class initiate you pass your bot instance

#

why does this always say unsupported image type whenever I try to add an animated emoji, it works with a normal one though ;-;

async with aiohttp.ClientSession() as ses: 
  async with ses.get(image_url) as r: 
      img_or_gif = BytesIO(await r.read())
      b_value = img_or_gif.getvalue()
      if r.status in range(200, 299): 
        await inter.guild.create_custom_emoji(image=b_value, name=emoji_name)
lost lichen
#

if i remove the bot = what should i put here in the wait_for then??

cosmic agate
slate swan
slate swan
#

i recommend you send the img first to see how it looks

slate swan
lost lichen
slate swan
slate swan
slate swan
left crater
#

how can i get only the video urls in channel history

stone beacon
#

That's an instance variable not class

slate swan
stone beacon
#

Nop variable is bound to the instance of the class

#
class Dog:
  arg = 5

That's bounded to the class

slate swan
lost lichen
slate swan
#

you have a point

slate swan
#

oof

maiden fable
#

👀

left crater
maiden fable
#

U gotta use regex or smth

#

Or use message.attachments

left crater
#

oh

maiden fable
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
maiden fable
#

!d filter

unkempt canyonBOT
#

filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.

Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.

See [`itertools.filterfalse()`](https://docs.python.org/3/library/itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
stone beacon
#

Murder she wrote!!

buoyant igloo
#

Guys I wanna put a huge part of my code into another file to use it how would I do that? (Discord.py)

slate swan
stone beacon
#

!d discord.utils.find

unkempt canyonBOT
#

discord.utils.find(predicate, seq)```
A helper to return the first element found in the sequence that meets the predicate. For example:

```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
```  would find the first [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") whose name is ‘Mighty’ and return it. If an entry is not found, then `None` is returned.

This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.9)") due to the fact it stops the moment it finds a valid entry.
slate swan
stone beacon
#

at that's it

buoyant igloo
maiden fable
slate swan
maiden fable
#

with?

left crater
#
async def jpg_File(message):
    channel = bot.get_channel(699577970117050399)
    messages = await channel.history(limit=None).flatten()
    for p in messages:
        print(p.attachments)```this extracts images and videos
stone beacon
stone beacon
#

I'd recommend using regex to match the video urls in the message content

maiden fable
#

wait what is the error?

left crater
#

sadly i dont know how to do that

maiden fable
#

Yea regex sucks ik

slate swan
maiden fable
stone beacon
#

Thankfully big brain peeps did most of the painful regex for us. If you make a quick google search you can "regex pattern to match links". The problem is, how do you differentiate between an image or video link I don't know how to do that

slate swan
stone beacon
#

It would be much easier if you were just checking for uploaded videos not links that point to videos

maiden fable
stone beacon
#

Well you see most links don't end in png or mp4 etc

maiden fable
#

if "png" in url

stone beacon
#

For example a youtube link , I mean the user knows that all youtube links "can" be videos, but some can be of channels so that's a problem.

maiden fable
#

Ah that way

stone beacon
maiden fable
#

Wait I thought only user uploaded vids and stuff

stone beacon
#

If it's random vids then it's problematic but if all the vids follow a strict format you can get all of em

maiden fable
#

Yea

stone beacon
#

So I'm assuming it's links

maiden fable
#

Ah okay (Sleepy asf rn, already 12 here)

maiden fable
#

Meh nah

#

BTW did it work?

slate swan
maiden fable
#

I mean, u just gotta change half a line 👀

maiden fable
#

show code

slate swan
#

mhm

slate swan
maiden fable
# slate swan

show whole traceback. u ain't using a startswith anywhere

slate swan
maiden fable
#

Smh just do raise error

slate swan
#

no

maiden fable
#

bruh

slate swan
#

lol

#

kek lol, just to upload custom emojis

maiden fable
#

she just tryna mess with my brain rn

slate swan
maiden fable
#

what is the extension of the image file

maiden fable
slate swan
slate swan
final iron
slate swan
final iron
unkempt canyonBOT
#

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

maiden fable
#

Indeed

slate swan
maiden fable
#

show yr code again

slate swan
#

mhm

slate swan
maiden fable
#

Rip my internet

#

Idrk cannot see any issue

halcyon onyx
#

hello

#

help!!!!!!!!!!!

maiden fable
#

with?

kind cargo
#

i need help aswell

halcyon onyx
#

if the while true is on the bot stop working how i multithered it

final iron
kind cargo
#

@final iron could i get help?

final iron
kind cargo
#

okay sorry

#

hello help please

rotund leaf
halcyon onyx
kind cargo
#

my problem is at the end on the code, if name == "main":
bot.run(TOKEN)

#

it does not work

vocal stag
#

Hi guys!

#

I might come back here not long i think

halcyon onyx
kind cargo
#

wait somthing is wrong with this: bot.run(TOKEN)

#

should i paste my discord bot token in there?

halcyon onyx
#

ofc

kind cargo
#

okay

#

im beginner

halcyon onyx
#

or u have to put --Token = "type it here"--

#

before the bot.run

potent spear
# halcyon onyx

whatever you're trying here is very basic and will lose progress once the bot restarts, just saying

kind cargo
#

@halcyon onyx

slim ibex
swift imp
#

My bot restarts 5 times. What could be the reason?

potent spear
slim ibex
#

just convention pretty sure

swift imp
#

how

potent spear
#

don't tell me you're using replit as hosting

kind cargo
#

@slim ibex

#

can we go PM?

slim ibex
#

no

kind cargo
#

oky

swift imp
kind cargo
#

can anyone help me

potent spear
swift imp
#

bot just reloads 5 times

potent spear
buoyant igloo
#

does anyone know how to save user data in discord.py after you stop running your IDE?

buoyant igloo
#

Wdym

final iron
#

A database

potent spear
final iron
#

Like sqlite3

swift imp
#

well, I have a code with on_ready and when the bot starts, it displays a message saying that the bot will start soon

potent spear
final iron
#

!pypi aiosqlite

unkempt canyonBOT
potent spear
kind cargo
#

can anyone help me please i have 1 error, its says: name 'name' is not defined

final iron
#

Pretty obvious

#

You haven't defined name

kind cargo
#

how do i do that?

final iron
#

Define name

buoyant igloo
#

Define name

kind cargo
#

in vsc terminal?

buoyant igloo
#

Define name

kind cargo
#

or cmd

final iron
#

In your code

kind cargo
#

okay

#

where in my code if name == main:
bot.run(TOKEN) here?

final iron
#

It's __name__

swift imp
# potent spear Don’t do stuff in on_ready tho, a simple print at most

I only have this codepy @bot.event async def on_ready(): print('Бот скоро будет запущен') await bot.change_presence(status = discord.Status.online, activity = discord.Game("h!хелп")) for guild in bot.guilds: for member in guild.members: users = { "member_id": member.id, "guild_id": guild.id, "name": member.name, "money": 0 } if collection.count_documents({"member_id": member.id, "guild_id": guild.id}) == 0: collection.insert_one(users)

kind cargo
#

still dosent work @final iron

final iron
#
if __name__ == "__main__":
    ...
final iron
#

The api can disconnect you

vocal stag
#

test]

swift imp
#

@final ironin name write the name of the bot file?

final iron
#

No

swift imp
#

just copy and paste it?

final iron
#

Not exactly

buoyant igloo
#

name is a function from python

final iron
#

But the if __name__ == "__main__": part

slate swan
#

@bot.command()
async def alex(ctx, arg):
  name, leng, amnt = arg.split(':')
  users = 0

  content = '\n'.join(sample(ascii_lowercase+digits, int(leng)))
  buffer = BytesIO(content.encode('utf-8'))
  file = discord.File(buffer, filename= name)
  users += 1
  print(f"{user} | {users}")
  ctx.send(file=file)``` discord not defined but it should from module?
kind cargo
#

Can i get som help: File "C:\Users\sweti\OneDrive\Skrivbord\swishbot\swishbot\main.py", line 50, in <module>
bot.run(TOKEN)

#

bot.run(TOKEN) what should i do ?

slate swan
#

You need to make token a string

mystic vault
slate swan
#

And change bot.token to your bot token from the link @mystic vault sent

mystic vault
kind cargo
#

yes

slate swan
#

Read what he said

kind cargo
#

alright

potent spear
left crater
#

@maiden fable i figured it out btw

slate swan
#

Create application

maiden fable
#
@bot.command()
async def ping(ctx):
    await ctx.send("|| Boomer ||")
slate swan
#

@bot.command()
async def ping(ctx):
await ctx.send('Pong! {0}'.format(round(bot.latency, 1)))

left crater
# maiden fable how

i took every attachment ever sent in the channel and converted it into a list then just did this for i in a: if i.endswith("mp4\n"): print(i)

maiden fable
#

That won't work everytime @left crater

kind cargo
#

@slate swan i didnt understand

maiden fable
#

Since sometimes there is a \ at the end too

slate swan
#

Yes

buoyant igloo
#

You need to define bot

kind cargo
#

could we go call or pm @slate swan

maiden fable
#

U should use if "mp4" in url

left crater
#

but i have a slight problem

swift imp
#

@potent spearokay thx

cloud dawn
maiden fable
#

tf is that

left crater
#

will that still send

swift imp
#

thanks for the help

cloud dawn
# maiden fable tf is that

mimetypes is a global way to check a files type. So if i were to rename a mp4 to mp3 mimetypes would still identify it as a mp4

maiden fable
#

Ah okay

slate swan
#

@bot.command()
async def alex(ctx, arg):
  name, leng, amnt = arg.split(':')
  users = 0

  content = '\n'.join(sample(ascii_lowercase+digits, int(leng)))
  buffer = BytesIO(content.encode('utf-8'))
  file = discord.File(buffer, filename= name)
  users += 1
  print(f"{user} | {users}")
  ctx.send(file=file)``` discord not defined but it should from module?
final iron
#

Can you send the traceback?

left crater
slate swan
final iron
#

Yes

left crater
#

is there anyway i can remove all of these spaces?

maiden fable
#

the line breaks?

left crater
#

ye

slate swan
honest shoal
#

👀

cloud dawn
left crater
#

i used a for loop to get all those links out

cloud dawn
left crater
#
for i in a:
    if i.endswith("mp4\n"):
        print(i)```
cloud dawn
#

You can remove \n in the list or modify the print function.

left crater
#

how

#

the list is too long

#

its like 2000 lines

cloud dawn
#
a = [links.mp4\n, link.mp4\n]
for i in a:
    if i.endswith("mp4\n"):
        print(i, end='')
#

!d print

unkempt canyonBOT
#

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)```
Print *objects* to the text stream *file*, separated by *sep* and followed by *end*. *sep*, *end*, *file*, and *flush*, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like [`str()`](https://docs.python.org/3/library/stdtypes.html#str "str") does and written to the stream, separated by *sep* and followed by *end*. Both *sep* and *end* must be strings; they can also be `None`, which means to use the default values. If no *objects* are given, [`print()`](https://docs.python.org/3/library/functions.html#print "print") will just write *end*.

The *file* argument must be an object with a `write(string)` method; if it is not present or `None`, [`sys.stdout`](https://docs.python.org/3/library/sys.html#sys.stdout "sys.stdout") will be used. Since printed arguments are converted to text strings, [`print()`](https://docs.python.org/3/library/functions.html#print "print") cannot be used with binary mode file objects. For these, use `file.write(...)` instead.
cloud dawn
# unkempt canyon

Look at the "end" kwarg default is \n with this code we just set it to a blank string.

left crater
#

ok let me see\

#

IT WORKS

#

thanks

gleaming torrent
#

Can bots use server emojis in their status?

final iron
gleaming torrent
#

oh wait

kind cargo
#

can i get some help

gleaming torrent
#

I can just test

kind cargo
#

ANYONE HELP ME

#

NameError: name 'name' is not defined

kindred epoch
kind cargo
#

iknow

#

but can i still get help?

slate swan
#

So learn basic Python and try building a Discord bot when you're more comfortable

kind cargo
#

okk

slate swan
#

We expect you to have a basic knowledge of Python.

#

Quick question, is there a way to make a new cooldown inside a command(im not talking abt @commands.cooldown()). Special cooldown for special ppl :)

slate swan
slate swan
slate swan
slate swan
#

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

slate swan
#

If you know wut im talking abt

#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
slate swan
#

No not really, you're not being very clear.

#

@bot.command()
async def alex(ctx, arg):
  name, leng, amnt = arg.split(':')
  users = 0

  content = '\n'.join(sample(ascii_lowercase+digits, int(leng)))
  buffer = BytesIO(content.encode('utf-8'))
  file = discord.File(buffer, filename= name)
  users += 1
  print(f"{user} | {users}")
  ctx.send(file=file)``` discord not defined but it should from module?
#

What kind of cooldown do you want to implement? Do you want the ratelimit to only apply once you've reached a certain point in the command's execution? You didn't provide any further clarification.

slate swan
slate swan
#

UGH idk how to explain it

#

😭omg

#

basically im using 1.7v

#

not 2.0

#

Hm.

#

!d discord.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cooldown "discord.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
rotund creek
slate swan
slate swan
#

new*

rotund creek
#

Also

slate swan
# slate swan ?

Send more code, it's pretty hard to debug that without more context.

rotund creek
#

I found a stackoverflow that might be useful for you @Saad#1337

slate swan
#

I'm not looking forward to guiding someone through the logic of implementing something like that lol

rotund creek
#

Let me get link brb

slate swan
#
@bot.command()
async def alex(ctx, arg):
  name, leng, amnt = arg.split(':')
  

  content = '\n'.join(sample(ascii_lowercase+digits, int(leng)))
  buffer = BytesIO(content.encode('utf-8'))
  file = discord.File(buffer, filename= name)
  ctx.send(file=file)
kind cargo
#

how to fix this problem NameError: name 'bot' is not defined

buoyant igloo
#

Define bot

kind cargo
#

how ?

buoyant igloo
#

bot = commands.Bot(command_prefix="pls ", help_command=None)

kind cargo
#

could we go pm?

buoyant igloo
#

K

kind cargo
#

i have sent u

final iron
#

Disallows other people to help and if someone gives you bad advice theres no one there to say its bad

slate swan
slate swan
rotund creek
#

@slate swan

slate swan
#

@kind cargo Also By the looks of it your not really familiar with python so I recommend docs

slate swan
#

you dont make a random instance of your bot?

slate swan
slate swan
rotund creek
slate swan
#

What line

slate swan
#

you define it with an instance of the class not another one

rotund creek
slate swan
slate swan
rotund creek
#

Check my code before answering.

rotund creek
#

Let me see

#

@slate swan 159

slate swan
#

Bruh

slate swan
#

I'm not asking for the line number, can you just show the line of code that failed

rotund creek
#

Okie

#

I think I found the error brb

scarlet aurora
#

is it possible to have a lot of bot commands in a separate file and import them all together as extensions through cogs? or only 1 command per .py file

final iron
#

You can put multiple commands in a cog

slate swan
#

Is there an easier library than nextcord regarding callbacks, and add_views? I am not so good with OOP.

#
online = len(list(filter(lambda x: x.status == discord.Status.online, mbrs)))                        
        print(f"{online}")
        idle = len(list(filter(lambda x: x.status == discord.Status.idle, mbrs)))
        offline = len(list(filter(lambda x: x.status == discord.Status.offline, mbrs))) 
        dnd = len(list(filter(lambda x: x.status == discord.Status.dnd, mbrs)))  
#

Shows the wrong number of people on the server (by status, there are intents)?

#

I wanna spawn those buttons based on multiple keywords. But I do not know the amount of buttons, before I query and online API. So its N amount of buttons and each needs a callback.

#
fits = ['1','2','3']

@bot.command()
async def tempest(ctx):
    message = await ctx.send("test")

    # Establish an instance of the discord.ui.View class
    view = nextcord.ui.View()

    for i in fits:
        view.add_item(item=nextcord.ui.Button(style=nextcord.ButtonStyle.link,label=str(i),url=message.jump_url))

    await ctx.send("pick a choice", view=view)

How would I know which button has been pressed?

manic wing
#

ⁿᵉˣᵗᶜᵒʳᵈ

slate swan
#

I am open to any other library 🙂

manic wing
#

use disnake

#

nextcord has a slow rate of development and has practically only changed the namespace

slate swan
#

I just checked the disnake example file for buttons, it shows how to make buttons if they are pre defined, but I need N amount of buttons (not hardcoded). How would I do that?

manic wing
#

typically you would want to avoid this and precode it in a class, but if necessary you would do ```py
view = disnake.ui.View()
for i in fits:
view.add_item(disnake.ui.Button(
style=disnake.ButtonStyle.green,
label=str(i),
url=message.jump_url,
)

slate swan
#

And how would you know which button has been pressed?

manic wing
#

im not sure if you can if your button is a url button but you would have to subclass Button to add a callback method

slate swan
#

The URL button was just an example, sorry. I do not need an URL button. After the user picked a button I want the bot to post an image.

scarlet aurora
#

how do i call multiple commands in a cog file

slate swan
#

How? I did not see any example code in stackoverflow or github that shows that for N amount of buttons 😦 Maybe I just missed it

#

I tried to find example code for this the last few days 😛

alpine furnace
slate swan
#

The buttons in that example are hardcoded. So the approach would not apply, would it?

scarlet aurora
#

load

slate swan
#

If I run that command in a for loop, it will overwrite the same button over and over.

#
fits = ['1','2','3']

@bot.command()
async def tempest(ctx):
    message = await ctx.send("test")

    # Establish an instance of the discord.ui.View class
    view = nextcord.ui.View()

    for i in fits:
        view.add_item(item=nextcord.ui.Button(style=nextcord.ButtonStyle.link,label=str(i),url=message.jump_url))

    await ctx.send("pick a choice", view=view)
#

Because the buttons are fetched from a database

#

Unknown before how many there are and what text they contain

#

Until the database query, correct.

#

But for simplification, lets assume I use a random number to define how many buttons there are.

#

Correct.

alpine furnace
#

Just make a lambda and map each letter in a dictionary

#

To a different lambda, that is

slate swan
#

So that is why I did not find anything on stackoverflow?

alpine furnace
#

Yes it would

#

Just set the callback argument in button to a lambda you generate each iteration

#

Not sure why you need a decorator as it’s just a plain function that’s called

#

Decorator* not callback

slate swan
#

I "just" need the value of the button (or know which button the user has pressed). The bot decides what to do next. Or is that oversimplyfied?

#

I saw on_component on stackoverflow

#

The Component Interaction Object

#

But I am terrible with classes 😛

alpine furnace
#

So forgive me, not lambdas, an async inner function 😄

#

And then in process you could access the button’s name

slate swan
#

🤯

#

await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1")

#

That looks similar

final iron
#

discord-components

alpine furnace
#

Eh, idk why you’d do that

final iron
#

😔

slate swan
#

I think actually parsing the discord json response would be easier for me, since I do know python (just not oop), but if for whatever reason I need to pass this code on to someone else in the future, I do not want to leave them with a mess.

final iron
#

Parsing json is simple, I personally don't think it would be a mess

slate swan
#

As a general questions, which is the most commonly used library? I see stackoverflow posts from dec 2021, using discord.py

alpine furnace
#

Pycord is good

#

It apparently has the most stars on GitHub from all the forks

alpine furnace
slate swan
#

Why do all those discord libraries look the same? 😳

alpine furnace
#

Lol

final iron
slate swan
#

Well, that makes sense.

zenith basin
#
    @commands.Cog.listener()
    async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
        guild_id = 915076185740939304
        # if they remove the reaction remove the role
        if payload.guild_id == guild_id:
            reaction_roles_data = self.reaction_roles_data[payload.guild_id]
            for reaction_role in reaction_roles_data:
                if reaction_role["emoji"] == str(payload.emoji):
                    role = discord.utils.get(payload.member.guild.roles, id=reaction_role["roleID"])
                    await payload.member.remove_roles(role)
                    break

error:

Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
  File "C:\Users\wolf\Trello\venv\lib\site-packages\discord\client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\wolf\Trello\cogs\Reaction.py", line 98, in on_raw_reaction_remove
    role = discord.utils.get(payload.member.guild.roles, id=reaction_role["roleID"])
AttributeError: 'NoneType' object has no attribute 'guild'
wild comet
#

trying to get my bot to send new players a message but it wont work

@client.event
async def on_member_join(member):
    await member.send("hello")```

```26.02 16:36:47 [Bot] Ignoring exception in on_member_join
26.02 16:36:47 [Bot] Traceback (most recent call last):
26.02 16:36:47 [Bot] File "/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
26.02 16:36:47 [Bot] await coro(*args, **kwargs)
26.02 16:36:47 [Bot] TypeError: on_member_join() missing 1 required positional argument: 'member'``` 
not really sure how to fix it
slate swan
#

you are missing an arguement

final iron
#

!paste

wild comet
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.

slate swan
#

on_member_join(ctx, member)

final iron
final iron
#

on_member_join doesn't take Context

zenith basin
#

nextcord or pycord ?

wild comet
#

uhh how do i check

final iron
#

Don't make any requests in on_ready
2.
requests is blocking, considering using aiohttp instead
3.
Consider using cogs

wild comet
#

i'll have a look thanks

hoary cargo
zenith basin
hoary cargo
#

!pypi disnake

unkempt canyonBOT
slate swan
outer parcel
#

can someone help me with this

#

it keeps on saying enable tracemalloc

#

but im not sure where i need to add that

final iron
outer parcel
#

because i do not need to await anything

final iron
#

🗿

final iron
outer parcel
#
line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 40, in tictactoe
    await ctx.send(embed=embed,view=view)
  File "/home/runner/Tuition/venv/lib/python3.8/site-packages/discord/abc.py", line 1368, in send
    raise InvalidArgument(f'view parameter must be View not {view.__class__!r}')
discord.errors.InvalidArgument: view parameter must be View not <class 'coroutine'>

The above exception was the direct cause of the following exception:
#
, line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: view parameter must be View not <class 'coroutine'>
/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine 'Command.__call__' was never awaited
  self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

done

slate swan
#

👁️👁️

outer parcel
#

oh i just realised error i forgo to callback

torn sail
outer parcel
#

wdym

pallid escarp
#

if message.embeds:
if "New Emote Appears" in message.embeds[0].title:
await message.channel.send('That Emote is HOT!')

I want it so my user bot sees other messages and not just its own how do i do that?

slim ibex
#

show more code

silent ermine
#

Would this code be the correct way to save something in sqlite

#
    @leveling.command()
    async def enable(self, ctx):
        db = sqlite3.connect('main.sqlite')
        cursor = db.cursor()
        cursor.execute(f"SELECT leveling_is_active FROM levels WHERE guild_id = '{ctx.guild.id}'")
        result = cursor.fetchone()
        #1 == yes && 0 == no
        if result == 1:
            sql = ("UPDATE levels SET leveling_is_active = ? WHERE guild_id = ?")
            val = (1, ctx.guild.id)
            cursor.execute(sql, val)
            db.commit
            await ctx.reply("Leveling is already enabled.")
            cursor.close()
            db.close()
        else:
            sql = ("UPDATE levels SET leveling_is_active = ? WHERE guild_id = ?")
            val = (1, ctx.guild.id)
            cursor.execute(sql, val)
            db.commit
            await ctx.reply("Leveling has been enabled.")
            cursor.close()
            db.close()```
Because it keeps saying `None` when i print the value
kindred epoch
#

and again, you used placeholders in some parts but not in the first part

kindred epoch
silent ermine
kindred epoch
# silent ermine

oh yea so for sqlite, you have to add an extra comma after the last arg like this
before:

,ctx.author.id,ctx.guild.id)

after

,ctx.author.id,ctx.guild.id,)
kindred epoch
#

idk its just like that for sqlite

slate swan
#

Prolly so code knows difference

kindred epoch
#

you dont have to do that in postgres tho

silent ermine
silent ermine
slate swan
#
@bot.command()
async def alex(ctx, arg):
  name, leng, amt = arg.split(':')
  
users = 0
name = name
leng = leng
amnt = amt
for i in range(int(amnt)):
        user = "".join(sample(ascii_lowercase+digits, int(leng)))
        users += 1
        print(f"{user} | {users}")
        buffer = BytesIO(user.encode('utf-8'))
        discord.File(buffer,filename=name)
 await ctx.send(file=file)
silent ermine
kindred epoch
slate swan
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

slate swan
#

It’s suppose to make txt files of strings depending on input

silent ermine
# kindred epoch can you show me ur code?
@leveling.command()
    async def disable(self, ctx):
        db = sqlite3.connect('main.sqlite')
        cursor = db.cursor()
        cursor.execute("UPDATE members SET user_id = ? WHERE guild_id = ?",ctx.author.id,ctx.guild.id,)
        result = cursor.fetchone()
        #1 == yes && 0 == no
        if result == 0:
            sql = ("UPDATE levelingenabled SET leveling_is_active = ? WHERE guild_id = ?")
            val = (0, ctx.guild.id)
            cursor.execute(sql, val)
            db.commit()
            await ctx.reply("Leveling is already disabled.")
            cursor.close()
            db.close()
        else:
            sql = ("UPDATE levelingenabled SET leveling_is_active = ? WHERE guild_id = ?")
            val = (0, ctx.guild.id)
            cursor.execute(sql, val)
            db.commit()
            await ctx.reply("Leveling has been disabled.")
            cursor.close()
            db.close()```
silent ermine
# slate swan It’s suppose to make txt files of strings depending on input

indent it

@bot.command()
async def alex(ctx, arg):
  name, leng, amt = arg.split(':')
  
users = 0
name = name
leng = leng
amnt = amt
for i in range(int(amnt)):
        user = "".join(sample(ascii_lowercase+digits, int(leng)))
        users += 1
        print(f"{user} | {users}")
        buffer = BytesIO(user.encode('utf-8'))
        discord.File(buffer,filename=name)
        await ctx.send(file=file)```
kindred epoch
#

you are not supposed to copy and paste the exact same thing i send

#

that wont even work because you dont have a table called "members" in ur db