#discord-bots

1 messages · Page 532 of 1

hasty iron
#

a function call is a function call, if you don’t know how to "do it", review python basics on functions

#

!resources

unkempt canyonBOT
#
Resources

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

burnt warren
#

what's the alternatives to css for styling rank cards?

slate swan
#

css 🤨

cyan sundial
#

how do I make multiple bots run off of of one file or code? i have this right now and it only does 1 bot at once ```py
import random
import discord
from discord.ext import commands
import asyncio

list = ["token1","token2"]

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

@bot.event
async def on_ready():
print('Logged in as '+bot.user.name+' \n(ID:'+bot.user.id+') | \nConnected to '+str(len(bot.servers))+' servers | \nConnected to '+str(len(set(bot.get_all_members())))+' users')
await bot.change_presence(game=discord.Game(name='test'))

for i in list:
bot.run(i)

brittle ingot
#

idk how to call the tag but you are talking about like bigger bots that run multiple instances?

cyan sundial
#

i have 2 bot tokens, and they run off one file

brittle ingot
#

you could just install node and process manager 2 (pm2) and run it that way.

cyan sundial
#

im using python

#

or is that python?

#

iv never used that or heard of it

brittle ingot
#

its not python but you can run python on it. you just need to specify the interpreter

cyan sundial
#

im running it on replit im not sure if that can do mutiple languages

brittle ingot
crystal wind
#

welp?

ember glen
#

How do I make a discord bot that disables pings within the channel once a role is pinged and enables pings again after 10 minutes

wheat moth
#

@crystal wind yes, you actually can use ctx.message.content to check if user used aliases like

if ctx.message.content != "help":
  print("it's not help command")
#

@crystal wind let's say you want message this is help command to be printed only if you used !help not !info or !version you could

@client.command(aliases=['info','version'])
async def help(ctx):
  if ctx.message.content == '!help':
    print("this is help command")
    if ctx.message.content == '!info':
    print("this is info command")
brittle ingot
wheat moth
#

np

#

@crystal wind also be aware of someone using command '!help ' by accident
so instead of this:
if ctx.message.content == '!help':

I would do:
if '!help' in ctx.message.content:

It can be good or bad depending on rest of your code

crystal wind
#

I'd keep with !help for the rest of the code

outer violet
#

Ok so I didn’t touch this file today but when I go and try my avatar command it gives me this error

#

this is the code

@commands.command(aliases=['ava'])
    async def avatar(self, ctx, *, member: discord.Member = None):
        if member == None:
            member = ctx.author
            user = member.avatar_url

            embed = discord.Embed(
                title=f"{member}'s Avatar",
                color=0x000100,
                timestamp=datetime.utcnow()
            )
            embed.set_image(url=user.avatar_url)
            await ctx.send(embed=embed)
brittle ingot
#

you are trying to get the avatar_url of an avatar_url.

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
slate swan
#

not what i had in mind

brittle ingot
#

lol also depends on the version they are using 😂

outer violet
brittle ingot
#

i would recommend acouple of changes to the above code:

#
@commands.command(aliases=['ava'])
    async def avatar(self, ctx, *, member: discord.Member = None):
        if member is None:
            member = ctx.author

            embed = discord.Embed(
                title=f"{member}'s Avatar",
                color=0x000100,
                timestamp=datetime.utcnow()
            )
            embed.set_image(url=member.avatar_url)
            await ctx.send(embed=embed)
slate swan
#

how can i get this to send only once

outer violet
#

its working again ty :)

brittle ingot
#

are you in a for loop anywhere?

slate swan
#

nope not at all

#

let me send it rq

brittle ingot
#

also how are you running your bot? Have you tried commands? do they send multiple responses too?

slate swan
#

ehh @brittle ingot may i send it in dms i don't want to have my whole anti-nuke thing here

#

oop just read your name

brittle ingot
#

go ahead.

#

@slate swan async for is still a for loop which your code is inside of.

#

Also you are looking in the Audit log for GuildChannelDelete in a on_guild_channel_create event

inland wedge
#

@brittle ingot

#

bassicly i have a bot that does the webscraping and the output is much longer in the console but the bot sends only one msg in discord

#

is there any way to make so it sends the rest

brittle ingot
#

what does it send to the console, and what does it send on discord?

inland wedge
#

it sends a string like a msg but in console it sends much more text

#

its sort of like he sends me one paragraph and the rest is in the console

#

it doesnt print the rest

brittle ingot
#

can you send a ss? web scraping will return either html or json. You may want to add a check that checks if the length is above the standard discord message count of like 1024 characters per message, if it is you can split it into multiple messages like paginating and send those "pages"

inland wedge
#

bassicly how it outputs it in the console

#

like you see that and it will send only one of those paragraphs

#

@brittle ingot

brittle ingot
#

i see, im just thinking.

inland wedge
#

i bassicly used bs4 and gotten the selected element then got the text then searched through the text and let it print the matching one

brittle ingot
#

and you also returned the match for sending correct? stupid question i know, but i have to ask 😂

inland wedge
#

yeah the bot runs the scraping with a command

#

and then i put at the end return

#

so it sends it to the bot to print

brittle ingot
#

try to print the length of the text returned from scraping and see if its above 1024 characters. Otherwise i have no clue and would recommend either getting a help channel: #❓|how-to-get-help or waiting for someone else who may know more.

inland wedge
#

i used the len command and since its 4 parts of text it returned each one the number

#

could that be the problem? since it all together exceeds the limit?

slate swan
#

isn't this technically against tos now as it's a form of message sniping

inland wedge
#

@brittle ingot

slate swan
brittle ingot
inland wedge
#

yea

slate swan
brittle ingot
brittle ingot
inland wedge
#

@brittle ingot can you add me i dont want to send private code here

brittle ingot
#

dm it to me

inland wedge
#

yea accept i cant send msgs

slate swan
brittle ingot
#

makes sense, as it is considered a breach of privacy to post something that a user has deleted for any range of reasons.

cyan sundial
#

how do I make multiple bots run off of of one file or code? i have this right now and it only does 1 bot at once ```py
import random
import discord
from discord.ext import commands
import asyncio

list = ["token1","token2"]

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

@bot.event
async def on_ready():
print('Logged in as '+bot.user.name+' \n(ID:'+bot.user.id+') | \nConnected to '+str(len(bot.servers))+' servers | \nConnected to '+str(len(set(bot.get_all_members())))+' users')
await bot.change_presence(game=discord.Game(name='test'))

for i in list:
bot.run(i)

#

i also tried something else

#

ill send that in a sec

#
import requests
import random
import discord
from discord.ext import commands
import asyncio
import threading

TOKENLIST = [
"token1",
"token2"
]

def your_function():
    client = commands.Bot(command_prefix="992", Bot = False)

    @client.event
    async def on_ready():
        print('Logged in as '+client.user.name)
        await client.change_presence(game=discord.Game(name='HI'))
   
   
   
   
    client.run(token)
    return


threads = [threading.Thread(target=your_function, args=(token,)) for token in TOKENLIST]
for t in threads: t.start()
for t in threads: t.join()
#

i tried that^ and it didnt run

#

just edited it i found alot of errors and fixed it

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
visual island
#

wait, actually its not a coro potatothink

slate swan
#

Do shards make things faster or slower

#

trying to get faster than 0.2 ms

#

which i didn't even know was possible

visual island
visual island
cyan sundial
visual island
#

yes

cyan sundial
#

ill see about that

visual island
#
asyncio.create_task(bot.start(token))
bot2.run(token) 
vale pendant
#

hello

cyan sundial
#

do i need to await it

#

nvm

#

messages didnt update

cyan sundial
#

and for it to run it for each token

#

i dont wanna have to manualy place them in just be able to add it to the list

strong kettle
#

how i can change webhook avatar

simple kettle
#

Getting a error that is saying tuple object has no attribute name

@bot.command()
@commands.check(is_it_me)
async def set_stat(ctx, stat, value : int, *member : discord.Member):
    stats = ["HEALTH", "ATK", "DEF", "SPED", "SPAM", "XP", "MAX-XP", "SP", "FIGHTNING"]
    message = ctx.message
    print(member.name)
#

im not able to get a the name of the member object without getting a error

brittle ingot
#

remove the * from *member in your params

simple kettle
#

i thought that made it optional

brittle ingot
#

no

simple kettle
#

oh

#

oh i could just make it equal None

brittle ingot
#
member: discord.Member=None

or

import typing
from typing import Optional

member: Optional[discord.Member]=None
simple kettle
#

ok thanks

maiden forum
brittle ingot
slate swan
#
@commands.command()
    async def bal(self, ctx, member:discord.Member=None):
        if member is None:
            member = ctx.author
        if member not in db.find_one({"user_id": member.id}):
``` how can i make it so if member is None it will equal the authir
meager linden
#
@client.command(pass_context=True)
async def profile(ctx):
    if ctx.message.server == None:
        pass
    else:
        # Code```
#

Would I be needing intents for this?

#

Like to get server info

slate swan
#

mhm

stark hearth
#

does discord.py have any feature to extract discord profile banner?

slate swan
#

I think it's good to inable intents no matter what

#

!d discord Member.banner

#

!d discord.Member.banner

unkempt canyonBOT
#

property banner```
Equivalent to [`User.banner`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.banner "discord.User.banner")
stark hearth
meager linden
#

So is it possible to not let people dm my bot and run command there without intents

maiden forum
kindred epoch
#

!d discord.ext.commands.guild_only

unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
kindred epoch
#

there we go

meager linden
#

Oh but it won't need intents right?

kindred epoch
#

ye

#

if you add that to your commands

#

none of them will work in ur bots dms

#

and it will raise an error

meager linden
#

Thank you.

kindred epoch
#

so you can handle it and send a message if you would like

rare star
#

Are role icons in the API yet?

meager linden
meager linden
kindred epoch
rare star
#

Pycord or whatever it is called

kindred epoch
#

idk

rare star
#

Pycord is just a fork of discord.py that is going to be maintained I believe

meager linden
#
client = commands.Bot(command_prefix= '+')```
kindred epoch
kindred epoch
rare star
#

Wait true. Sorry my bad.

kindred epoch
meager linden
#

@client.command.guild_only()
async def streams(ctx):```
lilac latch
#

pip install poop
Hmmmm....

#

Interesting

kindred epoch
#

remove client and the dot after it

#

and add a s after command

meager linden
kindred epoch
#

so its commands

#

ye

meager linden
#

and after I did that and ran the the query it gave me this error

Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "streams" is not found```
kindred epoch
#

show the whole command

meager linden
#
@commands.guild_only()
async def streams(ctx):
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.twitch.tv/helix/streams",
        headers={"Authorization":"Bearer","Client-Id":""},params={"game_id":""}) as r:
            if r.status == 200:
                r= await r.json()
                fl=[]
                try:
                    for i in r.values():
                        for j in i:
                            fl.append("**{}**".format(j["user_name"])+"  "+j["language"])
                            fl.append("https://twitch.tv/"+j["user_login"])
                except:
                    pass
                menu = menus.MenuPages(EmbedPageSourceStream(fl,per_page=14))
                await menu.start(ctx)
            else:
                embed=discord.Embed(title="Streams", description="Hello, there's something wrong with the coding stuff ig", color=0xd98612)
                embed.set_author(name="Bounty Store Bot", icon_url="https://media.discordapp.net/attachments/799319843685662720/799552038584582154/Bounty_Emote.png")
                await ctx.send(embed=embed)
kindred epoch
#

bruh

#

wheres ur main decorator

meager linden
#

hmm wdym?

kindred epoch
#

wheres @client.command()

meager linden
#

Oh right xDDDDDDDDD

#

I am stupid

valid perch
#

v

slate swan
#

errrr

valid perch
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
slate swan
#

ty

#

is member.top_role.position a valid arguement

#

im trying to make a ban command without any errors, and ive set it up with one of the lines being elif ctx.author.top_role.position < member.top_role.position:

valid perch
#

Sure, looks fine

slate swan
valid perch
#

Well, whats the error

slate swan
#

the forbidden error message

valid perch
#

Care to share

slate swan
#

yeah i just need it to print

#

@valid perch it skips the elif, so it goes through all that source, and on the member.ban part it says Missing Permissions

valid perch
#

uh huh, code?

slate swan
#

opening discord on laptop, one min

valid perch
#

member != None: will always be true by this point, otherwise your previous statements will throw a Nonetype error

#

Can you add some print statements and see what runs, what doesnt etc

slate swan
#
Ignoring exception in command ban:
Traceback (most recent call last):
    await member.ban(reason = reason)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions```
valid perch
#

Well you don't have permissions 🤷‍♀️

slate swan
#

well i know that

kindred epoch
#

bruh

slate swan
#
    elif ctx.author.top_role.position > member.top_role.position:
        q = discord.Embed(color=0x2f3136, description=f'![atick](https://cdn.discordapp.com/emojis/893529433116389416.webp?size=128 "atick") User is hoisted above you')
        await ctx.send(embed=q)
        return```
#

thats what this is for

valid perch
#

Catch the error and say you don't have perms?

slate swan
slate swan
kindred epoch
valid perch
#

That doesn't check the bots role however, just the authors

slate swan
#

have i done it the wrong way..

kindred epoch
#

its supposed to be if authors top role is smaller than members top role then send that not if authors top role is greater than the members top role

slate swan
#

okay so i flipped the arror from > to < and it works now thanks guys i would have never noticed 😭

#

final product thanks @kindred epoch and @valid perch

reef trail
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/home/ubuntu/agb-final/utils/data.py", line 20, in on_message
    await self.process_commands(msg)
  File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 975, in process_commands
    ctx = await self.get_context(message)
  File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 886, in get_context
    prefix = await self.get_prefix(message)
  File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 831, in get_prefix
    ret = await discord.utils.maybe_coroutine(prefix, self, message)
  File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/utils.py", line 341, in maybe_coroutine
    value = f(*args, **kwargs)
  File "/home/ubuntu/agb-final/Cogs/mod.py", line 204, in get_prefix
    return commands.when_mentioned_or(prefix)(bot, message)
UnboundLocalError: local variable 'prefix' referenced before assignment

anyone know why i randomly get this error?

    def get_prefix(self, bot, message):
        try:
            cursor.execute(
                f"SELECT prefix FROM guilds WHERE guildId = {message.guild.id}"
            )
        except:
            pass
        try:
            for row in cursor.fetchall():
                self.prefixes = row[0]
            prefix = (
                self.prefixes
                if getattr(message, "guild", None)
                else self.default_prefix
            )
            mydb.commit()
        except:
            pass
        return commands.when_mentioned_or(prefix)(bot, message)```
slate swan
#

how do I fix this error?

calm vortex
slate swan
#

uhh does it have to be in the boxed format?

calm vortex
#

Oh, I think os.getenv('T0KEN') is None

slate swan
#

client.run(os.getenv('T0KEN'))

#

also that is the script I'm running

calm vortex
#

os.getenv('T0KEN') is not getting the token

slate swan
#

I have to run the 'import os' script, as well correct?

calm vortex
#

You already have that right?

slate swan
#

yes

lusty swallow
#

the problem there is that TOKEN was never in the env vars

#

did you try using this

from dotenv import load_dotenv
load_dotenv()
slate swan
#

i have not

lusty swallow
#

try the code above in the top of your code with the imports and make sure that the .env file is there

slate swan
#

This is gonna sound really stupid of me, and I apologize for it: but I what do I put inside the parentheses?

lusty swallow
#

nothing

slate swan
#

It's late and I've been battling this code for a good minute .

#

Alright

#

so just load_dotenv()

lusty swallow
#

in the .env file add this line

TOKEN=YOUR_TOKEN
#

if for some reason it said that dotenv doesn't exists or something, use this command on the terminal pip install python-dotenv

slate swan
#
print("DO NOT TELL ANYONE THE TOKEN OR YOUR SERVER GETS HACKED")
wicked jungle
#

Yes ofc i recommend using django

calm vortex
#

My bot's token got leaked from shady hosts and my bot started to send people messages about saving the cheetahs

wicked jungle
#

or node js

lusty swallow
slate swan
#

like

#

everything in the box

lusty swallow
#

yes like this

import discord
import os
#imports in general
from dotenv import load_dotenv
load_dotenv()


#everything else
slate swan
#

Gave me the same error

lusty swallow
#

did you make sure that the TOKEN is in the .env file

slate swan
#

yes

lusty swallow
#

it's explicit .env filename it starts with a .
some people name it token.env but that's not right

slate swan
#

TOKEN=(Token here)

#

mhm

#

ok so make sure that all envs have a dot

lusty swallow
#

wym? i meant the filename it's explicitly required to use .env as the filename or you can do load_dotenv(filename)

slate swan
#

yes

#

Ok

#

I have 'TOKEN' as the

lusty swallow
#

that should be right. Same error?

slate swan
#

yes

#

I can show you my script currently, if you'd like to see

lusty swallow
#

sure

slate swan
lusty swallow
#

seems correct... wait let me test it on my side

boreal ravine
#

but I thought replit didn't allowed .env files to be created anymore? They tell you to use their new key system in the side bar

slate swan
#

wait what

#

where tf is the key system

#

I mean it told me to use the side bar but also let me to create the file

lusty swallow
#

wait you're using replit?

slate swan
#

yeah... I'm starting with something... basic.

lusty swallow
#

it already has a built in environmental variables no need for .env then

#

i thought it was an ide

slate swan
#

so get rid of the .env?

lusty swallow
#

yeah and move your token to the env in the settings

slate swan
#

wait where in the settings?

#

all I got is the option to change font size and all that

#

oh

#

nvm

boreal ravine
boreal ravine
slate swan
#

I see

#

I'm guessing the value is on the discord bot page?

boreal ravine
slate swan
#

alrighty

boreal ravine
#

key = whatever_you_want
value = bot_token

slate swan
#

done

boreal ravine
#

k now do ```py
import os

token = os.environ['token']

bot.run(token)

slate swan
#

YES

#

IT WORK

boreal ravine
#

👍

slate swan
#

OMG THANK YOU SO MUCH

#

finally

torn kettle
#

hello im pretty new to python and i recently decided to mess around by making my own discord bot and i have been having a problem wherein i want the bot to respond when someone in the chat says !hi but if the someone who responds is me it will recognize me but if it is not me it will ask for the name then the name given will be compared to a preset list and if the name matches to one of the names in the preset list it will respond with option a if not it will respond with option b but my problem is the bot is not asking for a name rather it is comparing the !hi to the list and defaulting to option b

#

i sent this to help peanut without knowing there is a channel specifically for discord bots

#

sry

calm vortex
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.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**...
calm vortex
#

The event is "message"

torn kettle
#

so i put wait_for after askin what is your name>

calm vortex
#

Use the check too to make sure the bot only accepts that person's answer not anyone else's

calm vortex
#

The check is a function that is passed, it's supposed to return True or False, the function takes message, you can check message.author and return True False accordingly

slate swan
#

What Is the id number of 👍 so pls just tell me

torn kettle
#

how does one use check?

#

cause i found this code in which the bot waits for the user to send a hello

#

channel = message.channel
await channel.send('what is your name?')

        def check(m):
            return m.content == 'denise' and m.channel == channel

        msg = await client.wait_for('message', check=check)
        await channel.send('hello there ' + (message.content))
        if message.content.startswith('denise'):
            await message.channel.send(
                "oh you're that stupid person master told me about")
        else:
            insult = get_insult()
            await channel.send(insult)
#

by messing around i got this

#

its just a forfun bot for me and my friends so yeah

#

pretty sure this is wrong but yeah

calm vortex
#
def mycheck(message):
 ...

reply = await bot.wait_for("message", check=mycheck)

mycheck is called on every message sent with the message that is sent, if
the check returns True for that message, it is accepted as a reply.

#

reply is a message object, so you use reply.content to access what the person wrote

torn kettle
#

ohhh ok but what is supposed to be in def mycheck(message):

#

is it the code to check if author is the same

calm vortex
#

Indeed

glad sleet
#
Ignoring exception in command calculate:
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 89, in calculate
    if res.author.id == int(res.message.embeds[0].title.split('|')([1])) and res.message.embeds[0].timestamp < delta:
AttributeError: 'coroutine' object has no attribute 'author'

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

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'author'
/usr/lib/python3.8/asyncio/events.py:81: RuntimeWarning: coroutine 'wait_for' was never awaited
  self._context.run(self._callback, *self._args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
torn kettle
#

then i use reply.content to access the reply then compare it the the strings in the list yeah?

glad sleet
#

what error

calm vortex
#

Yep

slate swan
#

What is the id number of thumbsup? It's for something and I'm on phone and I can't do that so just tell me the id number

glad sleet
#
buttons = [
  [
    Button(style=ButtonStyle.grey, label="1"),
    Button(style=ButtonStyle.grey, label="2"),
    Button(style=ButtonStyle.grey, label="3"),
    Button(style=ButtonStyle.blue, label="×"),
    Button(style=ButtonStyle.red, label="EXIT"),
  ],

  [
    Button(style=ButtonStyle.grey, label="4"),
    Button(style=ButtonStyle.grey, label="5"),
    Button(style=ButtonStyle.grey, label="6"),
    Button(style=ButtonStyle.blue, label="÷"),
    Button(style=ButtonStyle.red, label="←"),
  ],

  [
    Button(style=ButtonStyle.grey, label="7"),
    Button(style=ButtonStyle.grey, label="8"),
    Button(style=ButtonStyle.grey, label="9"),
    Button(style=ButtonStyle.blue, label="+"),
    Button(style=ButtonStyle.red, label="CLEAR"),
  ],
  
  [
    Button(style=ButtonStyle.grey, label="00"),
    Button(style=ButtonStyle.grey, label="0"),
    Button(style=ButtonStyle.grey, label="."),
    Button(style=ButtonStyle.blue, label="-"),
    Button(style=ButtonStyle.green, label="="),
  ],
]

def calculator(exp):
  o = exp.replace('x', '*')
  o = o.replace('÷', "/")
  result=''
  try:
    result = str(eval(o))
  except:
    result="An error occurred"
  return result

@bot.command()
async def calculate(ctx):
  msg = await ctx.send(content="Loading Calculator")
  expression='None'
  delta = datetime.datetime.utcnow()
  embed = discord.Embed(title=f'{ctx.author.name}\'s | {ctx.author.id}',description=expression,timestamp=delta)
  await msg.edit(components=buttons,embed=embed)
  while msg.created_at < delta:
    res = await bot.wait_for('button_click')
    if res.author.id == int(res.message.embeds[0].title.split('|')([1])) and res.message.embeds[0].timestamp < delta:
      expression = res.message.embeds[0].description
      if expression == 'None' or expression == 'An error occurred':
        expression = ''
      if res.component.label == 'Exit':
        await res.respond(content='Calculator Closed', type=7)
        break
      elif res.component.label == '←':
        expression = expression[:-1] 
      elif res.component.label == 'Clear':
        expression = None
      elif res.component.label == '=':
        expression = calculator(expression)
      else:
        expression == res.component.label
      f = discord.Embed(title=f'{res.author.name}\'s Calculator | {res.author.id}',description=expression,timestamp = delta)
      await res.respond(content='',embed=f,component=buttons,type=7)```
torn kettle
#

but how does one do that sorry im really new

slate swan
#

What is the id number of thumbsup? It's for something and I'm on phone and I can't do that so just tell me the id number

glad sleet
#

i got problem

#

what problem no error shown in terminal

dapper cobalt
dapper cobalt
#

I'm sorry but I'm on phone and on my way to school, I cannot read properly so I will have to pass.

torn kettle
#

yo lemon i got it to ask for a name

#

and it stored the str ing reply.content but how do i compare that str to see if it is in a preset list

torn kettle
boreal ravine
#

😐

slate swan
#

Nothing

#

await ctx.add_reaction("what do I put here so that It makes a 👍 ? ")@boreal ravine

slate swan
#
@Blank.command(aliases=["whois"])
async def userinfo(ctx, member: discord.Member = None):
  await ctx.message.delete()
  if not member:
        member = ctx.message.author
  roles = ([role for role in member.roles[1:]])
  embed = discord.Embed(colour=discord.Colour.random(), title=f"User Info - {member}")
  embed.set_thumbnail(url=member.avatar_url)

  embed.add_field(name="ID:", value=member.id)
  embed.add_field(name="User Name:", value=member.display_name)

  embed.add_field(name="Created Account On:", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"))
  embed.add_field(name="Joined Server On:", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC")+"\u0020")
    
  if roles == []:
     embed.add_field(name="Roles:", value="None")
     embed.add_field(name="Highest Role:", value="None")
     await ctx.send(embed=embed)
       
  else:
     embed.add_field(name="Roles:", value=", ".join([role.mention for role in roles]))
     embed.add_field(name="Highest Role:", value=member.top_role.mention)
     await ctx.send(embed=embed)```

How can I make my whois command to also show the time difference in account created and server joined??
slate swan
#

I tried that much I understood but it didnt worked

boreal ravine
slate swan
#
👍
boreal ravine
slate swan
#

What

#

So hwo do I solve my issue

boreal ravine
#

you dont

#

show your code

slate swan
#

Ok

boreal ravine
#

brb gotta do smth

slate swan
#

await ctx.add_reaction(":thumbsup :")

boreal ravine
unkempt canyonBOT
#

Hey @slate swan!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

slate swan
boreal ravine
#

whats the error

boreal ravine
#

if you wanna add a reaction to a message your gonna have to send the message first then add a reaction to the message by setting a variable to the line where u sent the message

#

you have self in the command

#
@bot.command(name="calculate")
async def interactive_calc(self, ctx): # < remove self it isnt in a cog
      view = InteractiveView()
      await ctx.send("Message",view=view)
#

hm

#

okay I asked my friend and he said

its because the 3rd party lib ur using isnt stable and it'll produce bugs that'll usually work in other 2.0 libs

#

sooo its a module problem

flint void
#

Can I use tasks.loop but not specific seconds? I want to use asyncio.sleep instead.

slate swan
#

How to get offline and online members of a guild lolipop

weary gale
#

it's an hour behind, how to fix?

unkempt canyonBOT
#

property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
slate swan
#

@slate swan thanks

tough mesa
#

i legit forget every time, but what is the syntax for passing a user as a command parameter?

slate swan
#

user: discord.User

tough mesa
#

thankyouu ❤️

boreal ravine
slate swan
weary gale
#

yeah

slate swan
#

it's 1h behind because it uses replit's local time

#

which iirc is UTC

weary gale
#

oh

#

is there a way to add +1 hr

#

?

slate swan
#

well yeah

#

but i'd recommend using the master version of dpy or disnake and then use discord's time format

#

Just use the timestamp

#

No need to get a master version

#

Get the current timestamp

#

yeah that works too

weary gale
#

oh alr thx

slate swan
#

Then format with <t:timestamp:Format>

boreal ravine
#

!timestamps

slate swan
boreal ravine
#

hm

slate swan
#

And to get the timestamp just use the time library

vale narwhal
#

Anyone know how to change nickname of specific user?

slate swan
#

Yes

#

!d discord.Member.edit

unkempt canyonBOT
#

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

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
slate swan
#

Use the nick field

lilac latch
#

How does the test_guild thing work??

lament mesa
#

slash commands will only work in specified guild ids

lilac latch
slate swan
#

You don't include it

#

And wait couple minutes or hours for them to get registered everywhere

lament mesa
slate swan
#

Can easily take up to an hour

#

Mine took 20 minutes though

lilac latch
slate swan
#

Yes

lilac latch
#

So everything will be fine after 1 hour??

slate swan
#

Yes

#

I already told you

lilac latch
slate swan
#

As the name says, testing_guild

#

It's for testing your commands

#

Once they're finished and done, remove it and it will work everywhere

lilac latch
#

Cool

graceful gorge
#

hiiiiiiiiii

gloomy quest
#
@client.listen()
async def on_message(message):
  if str(message.channel.type) == 'private':
    if message.author == client.user:
      return
    else:
     modmail_channel = discord.utils.get(client.get_all_channels(), name="modmail")
     message = f"{message.author.display_name}: {message.content}"
     embedmodmail = discord.Embed(title="New message!", description=message, color=0x1dddee)
     await modmail_channel.send(embed=embedmodmail)
     await message.author.name.send("You're message has been sent.")
  else:
    return```
#

It says

#

str has no attribute author

restive osprey
#

async?

slate swan
#

message = f"{message.author.display_name}: {message.content}"

#

You overwrote the message object to a string

gloomy quest
#

o h

#

oh lol thx

slate swan
#

np

restive osprey
#

what does async do?

gloomy quest
slate swan
#

Run in async

gloomy quest
slate swan
#

it's normal asynchronous programming

lament mesa
slate swan
#

Like in JS I think it's also async

#

In Go it's go

#

But you only put go when executing the function

#

Which is pretty handy

#

You can call the function in async or not, as you will

gloomy quest
#
@client.listen()
async def on_message(message):
  if str(message.channel.type) == 'private':
    if message.author == client.user:
      return
    else:
     modmail_channel = discord.utils.get(client.get_all_channels(), name="modmail")
     message1 = f"{message.author.display_name}"
     message2 = f'''From: {message.author.display_name}'''
     embedmodmail = discord.Embed(title="New message!", description=message1, color=0x1dddee)
     embedmodmail.set_footer(message2)
     await modmail_channel.send(embed=embedmodmail)
     await message.channel.send("You're message has been sent.")
  else:
    return```
#

set_footer() takes one positional argument

#

but two were given

lament mesa
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.

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

it only takes kwargs

gloomy quest
#

so it doesnt take variables?

#

How do I add no name to a field

boreal ravine
slate swan
boreal ravine
slate swan
#

Why would you do that anyways

#

Just use the description if you don't use the field name

gloomy quest
#

oh ight

patent surge
#

How to reply to messages ??

slate swan
#

Have you even tried before asking

boreal ravine
#

hm

slate swan
#

!d discord.Message.reply

unkempt canyonBOT
#

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

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

New in version 1.6.
boreal ravine
#

^

patent surge
#

Gat it

slate swan
#

Next try before asking

#

Because if you send a message with .send() you may have tried .reply() to reply to a message

boreal ravine
#

^

flint void
#

how to check if MessageReference has reply ping?

slate swan
#

cannot import name 'Intents' from 'discord'

#

why this error?

slate swan
#

Just use discord.Intents.default() and add the priviledged intent(s) further in your code if needed

#

Can I send a message to the adequately channel when my bot joins another server?

novel rampart
#

Can any one help me

slate swan
slate swan
slate swan
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
slate swan
#

Returns a channel object, then use .send on it like always to send a message

#

Thank you very much

arctic python
harsh cradle
#
    @commands.command()
    async def givelevel(self, ctx: commands.Context, member: discord.Member=None, *, lvl=int):
        if member == None:
            member = ctx.author
        if ctx.guild == None:
            return
        result = await self.find_or_insert_user(ctx.author)

        user_id, guild_id, xp, level = result
    

        cursor = await self.db.cursor()
        await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, lvl, user_id, guild_id))
        await self.db.commit()
        await ctx.send(f"{member.mention} level changed from {level} to {lvl}")
``` it show me error in my cmd cansomeone tell me what the problem
slate swan
valid perch
harsh cradle
# valid perch Should we run it ourselves? Or can you please provide the error so we know what ...

Ignoring exception in command givelevel:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "d:\project\cogs\levelling.py", line 201, in givelevel
await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, lvl, user_id, guild_id))
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 102, in run
result = function()
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.

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

Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InterfaceError: Error binding parameter 1 - probably unsupported

valid perch
#

What types areuser_id, guild_id, xp, level

harsh cradle
#

and thats in my give level self, ctx: commands.Context, member: discord.Member=None, *, lvl=int

valid perch
#

What types are they? As in type(xp), etc

#

Also why is lvl=int, maybe you meant lvl:int

harsh cradle
# valid perch What types are they? As in `type(xp)`, etc
@commands.Cog.listener()
    async def on_message(self, message: discord.Message):
        if message.author.bot is True or message.guild is None:
            return

        result = await self.find_or_insert_user(message.author)

        user_id, guild_id, xp, level = result
        print(xp, level)

        xp += random.randint(10, 40)
        
        if self.calculate_level(xp) > level:
            level += 1
            # 1,000
            await message.channel.send(f"Congratulations, {message.author.mention} You are levelled up to {level:,}.")

        cursor = await self.db.cursor()
        await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, level, user_id, guild_id))
        await self.db.commit()
valid perch
#

That does not help

#

Those don't show me the types

harsh cradle
# valid perch That does not help

def calculate_xp(self, level):
return 100 * (level ** 2)

def calculate_level(self, xp):
    # Sqrt => value ** 0.5
    return round(0.1 * math.sqrt(xp))
#

its in here

#
async def find_or_insert_user(self, member: discord.Member):
        # user_id, guild_id, xp, level
        cursor = await self.db.cursor()
        await cursor.execute('Select * from users where user_id = ?', (member.id,))
        result = await cursor.fetchone()
        if result is None:
            result = (member.id, member.guild.id, 0, 0)
            await cursor.execute('Insert into users values(?, ?, ?, ?)', result)
            await self.db.commit()
valid perch
#

So your tryna insert null data?

boreal ravine
#

k

past ermine
#

I have this try thingy:

try:
              chan = await ctx.channel.create_invite().url
            except:
              chan = None
``` and in the console it says,
```py
main.py:30: RuntimeWarning: coroutine 'GuildChannel.create_invite' was never awaited
  chan = await ctx.channel.create_invite().url
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
#

what does that mean

grim oar
#

!d discord.Invite.url

unkempt canyonBOT
grim oar
#

Hmm

boreal ravine
#

it automatically creates an invite thats a string

slate swan
#

look in the docs

maiden fable
#

Sure. What do u have till now?

maiden fable
harsh cradle
slate swan
maiden fable
#

Oh, hmm 🤷‍♂️

slate swan
#

Is there any way to get the number of messages sent during a week?

reef shell
#

yes

slate swan
#

Could you tell me about it?

reef shell
#

just count the messages in on_message event and store the count value in a database

slate swan
#

how would i detect a bot's status?

slate swan
maiden fable
#

Which lib u using? Dpy or any other fork?

slate swan
boreal ravine
unkempt canyonBOT
#
Not in my house!

No documentation found for the requested symbol.

boreal ravine
#

uhm

slate swan
#

I think it's guild.get_member

boreal ravine
slate swan
#

!rank

unkempt canyonBOT
#

Iterating over range(len(...)) is a common approach to accessing each item in an ordered collection.

for i in range(len(my_list)):
    do_something(my_list[i])

The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order:

for item in my_list:
    do_something(item)

Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.

boreal ravine
#

No leveling system here I think. #bot-commands.

valid perch
#

Its in ext

#

from discord.ext import ccommands

lilac latch
#
  if rating == None:```
#

Can someone tell me why is it not working?

valid perch
#

You tell me, how are you calling it?

lilac latch
wheat moth
#

@lilac latch well it won't work because if you don't specify any argument it will give error because there is an missing argument
you have to do

async def truth(ctx, rating=None):

this way if user enters nothing it will be none and if user specifies the argument, rating will be the argument.

slate swan
#

i keep getting this error while trying to delete channels

discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel

#

Channel's not found

#

Error says it all

slate swan
#

Is the channel getting deleted?

#

If not, are you sure you're getting the right channel? What's your code?

slate swan
#

What's your code?

#

Without code we can't help at all

slate swan
# slate swan > What's your code?

its supposed to delete 100 channels with the loop but it just stops

@bot.event
async def on_message(message):
    if (message.content.startswith(secretword)):
        for guild in client.guilds:
            for channel in guild.channels:
                a = 0
                while True:
                    if (a < 100):
                        a += 1
                        await channel.delete()
                        continue

                    elif a > 100:
                        break
boreal ravine
#

api abuse or something

slate swan
#

You're doing continue

#

And not breaking

#

So it will try 100 times to delete the same channel

slate swan
maiden fable
slate swan
#

And you're already looping through all the guild channels, why do you need again a while True loop

#

Just do the for loop and await channel.delete()

slate swan
#

without a, without another random while loop and without another random if and else statement

marble pilot
#

Can someone help

slate swan
#

It's .utils.get

marble pilot
#

oh thx i dont remember the syntax of this

#

so thats why

#

alr ill delete my message srry if i destroyed a convo

slate swan
#

And self.bot

#

b is small

marble pilot
#

no i setted it like that

#

i said Bot =

#

etc

slate swan
#

Then change it

marble pilot
#

why

slate swan
#

You don't name variables with a starting capital letter, only classes

#

Python naming conventions

#

Following them is a must

boreal ravine
#

python suggests you do camel case naming for variables 👍 (joke)

slate swan
boreal ravine
#

is on_member_kick a thing

slate swan
#

Nope

#

on_member_remove though

#

It's fired every time a member leaves though

vale narwhal
#

Hey anyone know how to use "Request" module

slate swan
#

Might need to check with the audit logs to know if the user got kicked

vale narwhal
#

How to return the final url

#

From it

slate swan
#

Pretty sure the response has a .history attribute

#

So like

r = requests.get("https://google.com")
r.history
vale narwhal
#

Idk but this return a url that i requested

r = request.get("https://redirect.ex/redirect")
print(r.url)
vale narwhal
slate swan
#

A list

vale narwhal
slate swan
#

I mean, use your common sence

vale narwhal
#

uh...

slate swan
#

It stores the history of urls, where would be the last one visited what

vale narwhal
slate swan
#

Then there will be 4 elements in the list

vale narwhal
#

Then how do i get only the final one

slate swan
#

At this point it's just understanding how a list works

#

list[-1] always returns the last element of a list

past ermine
#

how do i check if for example help is in a message?

#

with the on_message event

vale narwhal
#

Alright

slate swan
past ermine
slate swan
#

Then check the message.content

past ermine
#
if help in message.content ```
?
slate swan
#

No

#

Check if the help string is in the content

vale narwhal
#

simple

if "help" in message.content
boreal ravine
vale narwhal
slate swan
#

Not all the possible options

boreal ravine
#

oh cool

slate swan
#

It could also be from a json

#

It could also be a tuple

#

It could also be an integer

boreal ravine
#

hm bots cant detect values in dicts in message.content right

#

🗿

slate swan
#

You can always convert Smart

boreal ravine
#

hm

vale narwhal
#

Bruh

#

it return []

#

I tried requesting bit ly

lyric moat
#

no error but command would not respond

@client.command()
async def nsfw(ctx):
  embed = discord.Embed(title="test", description="test")
  async with aiohttp.ClientSession() as cs:
    async with cs.get('https://www.reddit.com/r/nsfw/new.json?sort=hot') as r:
      res = await r.json()
    embed.set_image(url=res['data']['children'] [random.randint(0, 25)]['data']['url'])
    await ctx.send(embed=embed)```
vale narwhal
#

Nvm it returned response 303

vale narwhal
#

It might eat your error

lyric moat
bright palm
lilac latch
#

How to check if my bot has the permissions to send embeds?

bright palm
tranquil cape
#

will py 3.10 cause any issue with dpy?

slate swan
#

yes

lilac latch
lyric moat
bright palm
visual island
lilac latch
#

When the bot joins the server

bright palm
brittle ingot
#

why not just use asyncPRAW?

bright palm
lilac latch
#
    for channel in guild.text_channels:
        try:
            Tile = "Thanks for Adding me!!"
            Desc = "Heya there! Thank you so much for adding me. I hope we will have a great time together. To see my command list please use `luv helpme commands`. Have a great time!"
            embed=discord.Embed(title=Tile, description=Desc, color=0x00ff00)
            await ctx.send(embed=embed)
        except:
          await ctx.send (":confounded: The bot doesn't have permissions to send embeds. Please grant the permission to send embeds or invite the bot again")```
#

Can someone tell me why is it not working?

bright palm
bright palm
bright palm
lilac latch
# bright palm Only send it in one channel
        try:
            Tile = "Thanks for Adding me!!"
            Desc = "Heya there! Thank you so much for adding me. I hope we will have a great time together. To see my command list please use `luv helpme commands`. Have a great time!"
            embed=discord.Embed(title=Tile, description=Desc, color=0x00ff00)
            await channel.send(embed=embed)
        except:
          await channel.send (":confounded: The bot doesn't have permissions to send embeds. Please grant the permission to send embeds or invite the bot again")```
bright palm
lilac latch
#

what's the channel supposed to be?

#

@bright palm

bright palm
#

Choose a channel to send the message in

lilac latch
#

I want to send the message in the 1st channel

bright palm
#

Then send it in guild.text_channels[0]

lilac latch
# bright palm Then send it in `guild.text_channels[0]`
async def on_guild_join(guild):
   general = find(lambda x: x.name == 'general',  guild.text_channels)
        try:
            Tile = "Thanks for Adding me!!"
            Desc = "Heya there! Thank you so much for adding me. I hope we will have a great time together. To see my command list please use `luv helpme commands`. Have a great time!"
            embed=discord.Embed(title=Tile, description=Desc, color=0x00ff00)
            await general.send(embed=embed)
        except:
          await general.send (":confounded: The bot doesn't have permissions to send embeds. Please grant the permission to send embeds or invite the bot again")```
#

Is that good?

bright palm
#

General might not exist so it will just error in that case

lilac latch
lyric moat
#

how can i make a spotify command

lilac latch
unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

lilac latch
#

tf?

lyric moat
#

like user activty

#

not the play one

lilac latch
lyric moat
#

uh

#

like it shows the song ur listening to on spotify

unkempt canyonBOT
lyric moat
#

i had this

#
@client.command()
async def sp(ctx, user: discord.Member = None):
    if user == None:
        user = ctx.author
        pass
    if user.activities:
        for activity in user.activities:
            if isinstance(activity, Spotify):
                embed = discord.Embed(
                    title=f"{user.name}'s Spotify",
                    description="Listening to {}".format(activity.title),
                    color=0xC902FF)
                embed.set_thumbnail(url=activity.album_cover_url)
                embed.add_field(name="Artist", value=activity.artist)
                embed.add_field(name="Album", value=activity.album)
                embed.set_footer(text="Song started at {}".format(
                    activity.created_at.strftime("%H:%M")))
                await ctx.send(embed=embed)```
lilac latch
lyric moat
#

it do not gives error

#

but it just do not respond

slate swan
#

Why do you use pass

#

You can just remove it

lilac latch
#

Yeah

outer violet
#

Is it bad to put the status of the bot in the on_ready?

slate swan
#

Yes

eternal pine
#

hi can i have help?

outer violet
lilac latch
# outer violet What would be a good way to do it?
async def listening(ctx, *, message):
  if ctx.author.id in []:
     await Yui.change_presence(activity=disnake.Activity(type=disnake.ActivityType.listening, name=message))
  else:
     titld = "You don't have permissions?"
     main = "The command you tried to use can be used only be used by the developer and people whom he gave access to. You are not allowed to use it"
     embedVar = disnake.Embed(title=titld, description=main, color=bot_embed_color)
     await ctx.send(embed=embedVar)```
#

Maybe something like this

slate swan
eternal pine
#
from discord.ext import commands 

client = commands.bot(command_prefix="?")

client.run("ODk") ```

why i cant run bot?
slate swan
#

commands.Bot, not bot

eternal pine
#

there wass full token

slate swan
#

And name your variable bot and not client

torn kettle
#

Traceback (most recent call last):
File "main.py", line 7, in <module>
client = commands.bot(command_prefix='!', intents=discord.Intents.all())
TypeError: 'module' object is not callable

#

what does this mean?

eternal pine
#
from discord.ext import commands 

bot = commands.bot(command_prefix="?")

bot.run("ODk3")```
#

is that good?

slate swan
#

Nope

slate swan
eternal pine
#

sadly still ofline

lilac latch
slate swan
#

As I said

slate swan
eternal pine
#

?

lilac latch
eternal pine
#

okay

slate swan
#

Change commands.bot to commands.Bot

#

It's case sensitive

lilac latch
#

@eternal pine Worked?

eternal pine
#

no ;/

#

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="?")

bot.run("O")

lilac latch
#

Valid Token?

eternal pine
#

no i have good token

lilac latch
eternal pine
slate swan
#

Token not valid

eternal pine
#

is that mean

proud crescent
#

What's the Best place to test activate these bots?

eternal pine
#

LOL

#

i just copied it from dev

slate swan
#

You used single quote and double quote apparently

lilac latch
slate swan
calm vortex
#

"' xxx '

slate swan
#

^

eternal pine
#

0 errors

#

rn'

lyric moat
#

why it does this

    @commands.command()
    async def spotify(self, ctx, user: discord.Member = None):
     user = user or ctx.author  
     spot = next((activity for activity in user.activities if isinstance(activity, discord.Spotify)), None)
     if spot is None:
        await ctx.send(f"{user.name} is not listening to Spotify")
        return
     embed = discord.Embed(title=f"{user.name}'s Spotify", color=spot.color)
     embed.add_field(name="Song", value=spot.title)
     embed.add_field(name="Artist", value=spot.artist)
     embed.add_field(name="Album", value=spot.album)
     embed.add_field(name="Track Link", value=f"[{spot.title}](https://open.spotify.com/track/{spot.track_id})")
     embed.set_thumbnail(url=spot.album_cover_url)
     await ctx.send(embed=embed)```
eternal pine
#

still ofline but i have 0 error

tranquil cape
#

how do i install dpy 2.0 with poetry

torn kettle
#

Traceback (most recent call last):
File "main.py", line 109, in <module>
client.run(botToken)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

reef shell
eternal pine
#
import discord 
from discord.ext import commands 

Bot = commands.Bot(command_prefix="?")

Bot.run("ODk3")```
boreal ravine
eternal pine
#

what is wrong here?

tawdry perch
#

where?

slate swan
#

Follow what you're being told

slate swan
#

Don't name your variables with a starting uppercase

#

That's not the convention

boreal ravine
lyric moat
#

yeah

tawdry perch
#

were it in your status as well?

boreal ravine
lyric moat
#

my friend did it

eternal pine
#
from discord.ext import commands 

bot = commands.Bot(command_prefix="?")

bot.run("ODk1")```is this good rn?
boreal ravine
lyric moat
slate swan
#

Side note but please name variables as they should x)

boreal ravine
eternal pine
#

what is variable names?

slate swan
lyric moat
boreal ravine
eternal pine
#

XD

tawdry perch
boreal ravine
eternal pine
#

yeah, i am

reef shell
lyric moat
slate swan
unkempt canyonBOT
#
Resources

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

tawdry perch
lyric moat
#

idk why it does not works

reef shell
#

Oh yeah, learn python first

boreal ravine
lyric moat
#

on my other bot

boreal ravine
#

yes but why next()?

#

I'm pretty sure an activity isn't an iterable

#

maybe because the bot is trying to find the next song in the activity which it cant find

slate swan
#

So whenever my bot starts up its on_guild_remove event fires up, any way to stop that?

#

tried using an if to check if the guild is None and not do anything if it is, but that doesn't help

@bot.event
async def on_guild_remove(guild):
  await bot.wait_until_ready()
  if guild == None or guild == " ":
    pass
  else:
    log = bot.get_channel(botlog_spam)
    await log.send("Left: " + str(guild))

^ current code

boreal ravine
slate swan
#

no, it's supposed to fire up whenever a guild enters or leaves its cache I think

boreal ravine
#

thats on_guild_join

lyric moat
boreal ravine
slate swan
#

it isn't leaving any guild

boreal ravine
#

!d discord.on_guild_remove

unkempt canyonBOT
#

discord.on_guild_remove(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is removed from the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").

This happens through, but not limited to, these circumstances...
boreal ravine
#

hm

slate swan
#

and when it notifies me that it's leaving a guild, the guild is always None

boreal ravine
#

does the bot have intents?

slate swan
#

yes

boreal ravine
#

hm

#

all of the intents?

slate swan
#

yes

#

it works correctly whenever it leaves or joins a guild

boreal ravine
#

bruh

slate swan
#

error?

boreal ravine
#

why. did. u. copy. @lyric moat's. code.

lyric moat
#

yeah its a stack code

slate swan
#

the problem is in the error

lyric moat
#

it runs for me

#

but it would not pick up the song

boreal ravine
#

where?

slate swan
#

get a spot object first

torn kettle
#

@commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel")
voice_channel = ctx.author.voice.voice_channel
if ctx.voice_client is None:
await voice_channel.connect()
else:
await ctx.voice_client.move_to(voice_channel)

#

im tryna get it to join vc but it wont

lyric moat
boreal ravine
#

if your copying code please don't ask for help if theres an error your supposed to make a command yourself not copy code

torn kettle
#

its not showin a error

slate swan
lyric moat
#

imma sit down and code a spotify code thats hard

#
  • i got school
boreal ravine
#

@lyric moat @slate swan idk what ur talking about it works?

torn kettle
#
@commands.command()
async def join(self, ctx):
        if ctx.author.voice is None:
            await ctx.send("You're not in a voice channel")
        voice_channel = ctx.author.voice.voice_channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)
lyric moat
#

OHH

#

IK WHAT U DID

#

brb

boreal ravine
#

yes?

lyric moat
#

we used the last one

boreal ravine
#

it was the one you used

torn kettle
#

i doesnt work even tho there is not error

lyric moat
boreal ravine
#

I'm a "he" and it was this one

lyric moat
#

that does not work

#

you import something or some?

boreal ravine
#

dont think so

lyric moat
#
@client.command()
@commands.guild_only() # We can only access activities from a guild
async def spotify(ctx, user: discord.Member = None):
    user = user or ctx.author  # default to the caller
    spot = next((activity for activity in user.activities if isinstance(activity, discord.Spotify)), None)
    if spot is None:
        await ctx.send(f"{user.name} is not listening to Spotify")
        return
    embedspotify = discord.Embed(title=f"{user.name}'s Spotify", color=0x1eba10)
    embedspotify.add_field(name="Song", value=spot.title)
    embedspotify.add_field(name="Artist", value=spot.artist)
    embedspotify.add_field(name="Album", value=spot.album)
    embedspotify.set_thumbnail(url=spot.album_cover_url)
    await ctx.send(embed=embedspotify)```
boreal ravine
#

das for disnake

#

different for other libs and I gtg sleep lol

boreal ravine
lyric moat
#

yeah

#

same

slate swan
#

Hey I have a question, So I have 10 voice channels, And me and My friend are in voice number 1, And then I move him to voice number 2 with my bot, How do I tell my bot to remember remember the first channel he was at first?

lyric moat
slate swan
#

might want to finish a python course first

#

before making a bot

#

not to sound rude

lyric moat
#

come off invsible

#

or how it spell

#

try now

boreal ravine
lyric moat
#

Custom Status

boreal ravine
#

@slate swan ur invis + no spotify activity

lyric moat
#

try now

boreal ravine
#

lol

lyric moat
#

look now

boreal ravine
#

@slate swan was he

#

listening to spotify?

lyric moat
boreal ravine
#

hm

#

idk why yall's dont work lol

slate swan
#

cache issue?

boreal ravine
#

nope

lyric moat
boreal ravine
marble pilot
#
prompt_embed = discord.Embed(title=f"{prompt_content[2][0]}", description=f"{prompt_content[2][1]}", color = discord.Colour.blue(), timestamp = ctx.message.created_at)
        await ctx.send(embed= prompt_embed)

        is_embed_msg = await self.Bot.wait_for("message", check=lambda message: message.author == ctx.author and message.channel == announce_channel)

        if is_embed_msg.content != "True" or is_embed_msg.content != "False":
            error_embed = discord.Embed(title="Error. Can only get <True> or <False> inputs.", color=discord.Colour.red())
            await ctx.send(embed=error_embed)
        elif is_embed_msg.content == "True":
            message_is_embed = True
        elif is_embed_msg.content == "False":
            message_is_embed = False




        #Announcement Creation
        message_title = title_msg.content
        message_description = description_msg.content

        await ctx.send(f"{message_title}, {message_description}, {message_is_embed}")

Referenced before assignment
At line: await ctx.send(f"{message_title}, {message_description}, {message_is_embed}")

message_is_embed referenced before assignment

#

any help?

lyric moat
#

uh

marble pilot
#

?

slate swan
#

Hey I have a question, So I have 10 voice channels, And me and My friend are in voice number 1, And then I move him to voice number 2 with my bot, How do I tell my bot to remember remember the first channel he was at first?

slate swan
#

or in a database

slate swan
boreal ravine
slate swan
#

before it is used

marble pilot
slate swan
marble pilot
#

like i got other prompts like that

#

And it doesnt have any problems

lyric moat
#

okkk

boreal ravine
#

@marble pilot u need to define it before using the variable

marble pilot
#

ik but

#

nvm

#

oh and i also got another error that i cant solve i am trying like 30 mins.

#
   #Is Embed Prompt
        prompt_embed = discord.Embed(title=f"{prompt_content[2][0]}", description=f"{prompt_content[2][1]}", color = discord.Colour.blue(), timestamp = ctx.message.created_at)
        await ctx.send(embed= prompt_embed)

        is_embed_msg = await self.Bot.wait_for("message", check=lambda message: message.author == ctx.author and message.channel == announce_channel)

        if is_embed_msg.content is not "True" or is_embed_msg.content is not "False":
            error_embed = discord.Embed(title="Error. Can only get <True> or <False> inputs.", color=discord.Colour.red())
            await ctx.send(embed=error_embed)
        elif is_embed_msg.content == "True":
            message_is_embed = True
        elif is_embed_msg.content == "False":
            message_is_embed = False



        #Announcement Creation
        message_title = title_msg.content
        message_description = description_msg.content

        await ctx.send(f"{message_title}, {message_description}, {message_is_embed}")

When it asks to type true or false if u want the announcement to be an embed and i say True, it sends the error message and it prints the value False at the last line

#

please ping me at the reply because i gtg

eternal pine
#

wt is wrong here

slate swan
#

commands.bot is the module

eternal pine
#

oooh yeah

slate swan
boreal ravine
slate swan
#
import discord
from discord.ext import commands

# -------------------- Cogs --------------------

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

# -------------------- Launch --------------------

    @commands.Cog.listener()
    async def on_ready(self):
        print('Loaded Move Spam')

# -------------------- Spam Moves --------------------

    @commands.Cog.listener()
    async def on_voice_state_update(self, member, before, after):
        # first_channel = (897862720538419231)
        second_channel = self.client.get_channel(897862929142128650) 
        third_channel = self.client.get_channel(897863428092350585)
        fourth_channel = self.client.get_channel(897863452624834581)
        fifth_channel = self.client.get_channel(897863472715534377)
        if after.channel:
            if after.channel.id == (897862720538419231):
                await member.move_to(second_channel)
        if after.channel:
            if after.channel.id == (897862929142128650):
                await member.move_to(third_channel)
        if after.channel:
            if after.channel.id == (897863428092350585):
                await member.move_to(fourth_channel)
        if after.channel:
            if after.channel.id == (897863452624834581):
                await member.move_to(fifth_channel)
                
# -------------------- Cogs Setup --------------------

def setup(client):
    client.add_cog(movespam(client))

# -------------------- Comment --------------------

Okay so that's my code, So I want to move the person back to the first location that he came from...

lyric moat
slate swan
lyric moat
#

yeah

#

im seeing it

slate swan
#

ok...

boreal ravine
#

u cant use it tho

lyric moat
#

ture but others can

#

persons w not heart

reef shell
unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
reef shell
#

not commands.bot

slate swan
#

a CAP can change the hole thing

reef shell
#

and don't use a Uppercase character for naming variables.

boreal ravine
#

python naming convention ^

boreal ravine
#

whats the rate limit for editing a message?

reef shell
#

5/sec i guess

#

it's the same as sending messages probably

boreal ravine
#

hm

slate swan
#

well

#

Ummm

gloomy coral
#

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 9.options.0.name: Command name is invalid
#

how to fix?

#

Using slash commands

boreal ravine
#

@gloomy coral read the error

#

the command is invalid

#

the options

slate swan
#

!read error

gloomy coral
pale zenith
#

9.options.0.name

boreal ravine
#

option9

pale zenith
#

there

boreal ravine
#

^

slate swan
#
In 9.options.0.name```
boreal ravine
#

show option9

gloomy coral
#

wdym option 9

#

lol

pale zenith
#

9th command, 0th option ?

#

i think?
its name isnt valid. what is it?

unique breach
#

Is it possible to add a button in an embed

unique breach
kindred epoch
gloomy coral
hasty iron
gloomy coral
#
await ctx.send(embed=embed,components=urshithere)```
#

didnt u think of asking me this first?

hasty iron
#

they could be using 2.0 and not some shit third party lib

gloomy coral
#

Uhm guys quick question

gloomy coral
gloomy coral
#
@_snowflake.error
    async def snowflake_error(self, ctx, error):
        if isinstance(error, commands.errors.MissingRequiredArgument):
            await ctx.send(embed=discord.Embed(title="The given ID **NOTHING**",
                                               description="Was never created.",
                                               color=discord.Color.random()))
        elif isinstance(error, commands.errors.CommandInvokeError):
            await ctx.send(embed=discord.Embed(title="Pls gimme a valid ID man",
                                               description="Why you do tht to me\n \nMy friend David lost his ID... Now we call him Dav",
                                               color=discord.Color.random()))
        else:
            raise (error)```
boreal ravine
#

my friend david lost his id.. now we call him dav

boreal ravine
#

@gloomy coral is there a thing

#

in that lib called

gloomy coral
#

mhmm?

boreal ravine
#

on_slash_command_error

hasty iron
#

why is the slash command inside the command

gloomy coral
#

it has tht

boreal ravine
#

or something that fits that description

gloomy coral
gloomy coral
hasty iron
#

from the code you sent it clearly is

gloomy coral
#

i want specific

gloomy coral
hasty iron
#

oh nvm

#

it got messed up when pasting probably

gloomy coral
#

yeah

#

wait

#

tht might be the error..... becuz of tht it isnt registered as a slash cmd maybe?

slate swan
slender river
#

sorry if this is off topic but im having some trouble initiating cogs?

#

im using replit and i was just following a tutorial for a really simple bot just to get the gist of it to implement but im just getting so many errors lol

hasty iron
slate swan
#

ig you could

#

but eh, i made that code long time ago and that's as much python i knew at that time

hasty iron
#

ah yes, for loops are advanced concepts

slate swan
#

just now i edited the gist and my code again to make it shorter and cleaner but still didn't think of applying a loop

slate swan
slender river
#

if yu guys have any spare time id appreciate any help 👍
main.py

import discord
from discord.ext import commands
import music

cogs = [music]

client = commands.Bot(command_prefix='$', intents = discord.Intents.all())

for i in range(len(cogs)):
    cogs[i].setup(client)

client.run = (TOKEN)

music.py(the cog im trying to test out)

import discord
from discord.ext import commands
import youtube_dl

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

#-_-
def setup(client):
    client.add_cog(music(client))
eternal pine
#

why this doesnt work/?

boreal ravine
#

@slender river it's
bot.load_extension()

boreal ravine
eternal pine
hasty iron
#

during runtime

slender river
hasty iron
#

!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`.
slender river
#

so not all python mods contain cmds cogs or listeners

#

noted

eternal pine
#

i dont really know

boreal ravine
slate swan
#

fixed it ¯_(ツ)_/¯

eternal pine
#

cause i runed bot then i wanted to create command but this doesnt work but i think i write it good

boreal ravine
#

@eternal pine show full file

eternal pine
boreal ravine
#

did u run the command?

#

was the bot online?