#discord-bots

1 messages · Page 1038 of 1

slate swan
#

shipit i hate fetch methods

#

ah

#

ohh

#

your bot is not in that server

ebon island
#

That is an api response

heady sluice
#

that's not the reason but yes

slate swan
slate swan
winged bone
slate swan
#

and.....it didnt do anything

#

atleast for me.

slate swan
winged bone
slate swan
#

yo bro 🗿the id should be the role id/ user id
not a channel id

slate swan
potent spear
slate swan
#

hm

slate swan
#

context.guild_id preferably

potent spear
slate swan
#

Or just look into some wrapper's source

slate swan
potent spear
unkempt canyonBOT
#

discord/guild.py lines 868 to 872

@property
def default_role(self) -> Role:
    """:class:`​Role`​: Gets the @everyone role that all members have by default."""
    # The @everyone role is *always* given
    return self.get_role(self.id)  # type: ignore```
potent spear
#

nice to know what's behind that attribute ig

#

still, I would always prefer guild.default_role.id over guild.id when trying to get the @everyone role id

slate swan
#

@slate swan am I being dumb again or smth? 😔 it wont work

#

nor any errors

slate swan
slate swan
#

.....Type.MEMBER for a role

slate swan
#

pithink you should sleep

slate swan
slate swan
#

i cant cuz im in school🏂

sick birch
slate swan
# sick birch and

and school is for studying so stay in school kids so your examples arent as bad as Robins!

boreal ravine
austere gust
#
async def on_message(message):
    if message.channel.id == 970295286851305482:
        await message.delete()
    else:
        return

    suggestEmbed = discord.Embed(colour=0xfecb01)
    suggestEmbed.set_author(name =message.author, icon_url= message.author.avatar.url),
    suggestEmbed.add_field(name= 'Ötlet', value= message.content)

    message = await message.channel.send(embed=suggestEmbed)
    await message.add_reaction('\N{WHITE HEAVY CHECK MARK}')
    await message.add_reaction('\N{CROSS MARK}') ```
Hello. When I write in the channel (970295286851305482) I get this error
maiden fable
#

Eh

#

Wait I think I know the issue

#

It's cz u r sending the message again to the same msg and the bot is deleting it again

rapid knoll
#

how to you use !discord ?

maiden fable
#

Add this line at the top:

if message.author == bot.user:
    return
maiden fable
unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

sick birch
#

You need the class that a method or property is of

quaint epoch
#

!d discord.Role

unkempt canyonBOT
#

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

There

rapid knoll
#

ok

quaint epoch
#

eh

#

bad bot

sick birch
#

It’s not as intuitive as the one they have in d.py but it works

rapid knoll
#

Ive just never used the bot before

quaint epoch
#

!d disnake.Role

unkempt canyonBOT
#

class disnake.Role```
Represents a Discord role in a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild")...
quaint epoch
#

(slap) BAD BOT!

sick birch
#

It does require you to know the classes methods and attributes are part of so you’ll usually see people helping using those commands

maiden fable
#

Like I learnt from seb and Robin

slate swan
#

ok so i have this code to uh set log channels for different servers
`

    with open('logchannel.json', 'r') as f:
        logchannels = json.load(f)
    return logchannels[str(message.guild.id)]
@bot.command()
async def setthelogchannel(ctx, logchannel):
    with open('logchannel.json', 'r') as f:
        logchannels = json.load(f)

    logchannels[str(ctx.guild.id)] = logchannel

    with open('logchannel.json', 'w') as f:
        json.dump(logchannels, f)
    await ctx.send(f"Changed the logchannel to {logchannel}")```
and when i set it in a event :
```@bot.event
async def on_message_delete(message):
    embed = discord.Embed(title=f"deleted message!")
    embed.add_field(name= message.content,value=f"Deleted Message: {message.content} by {message.author} ", inline=True)
    logchanneld = bot.get_channel(int(logchannel))
    await logchanneld.send(embed=embed)``` can anyone help?
sick birch
#

What’s the issue?

#

Also obligatory you should use a database not JSON

slate swan
#

yes but my issue is that logchannel is used as a parameter in a def function and i cant call it in anywhere else so is there like anyway i can call it somehow? and i cant use global for that because it is used as a parameter

rapid knoll
#

when using defs does it matter what you name it ?

slate swan
#

I'm making a discord bot and I made a embed but it's not working I tried to make a new bot with few commands like ping and test but the bot is not replying

@bot.command()
async def help(ctx):
    if ctx.channel.type != discord.ChannelType.private:
        if ctx.channel.id == 973394572627562506:
            embed=discord.Embed(title="Help", description=".", color=0x71368A)
            embed.set_thumbnail(url=ctx.guild.icon_url)
            embed.add_field(name="tt", value="tt", inline=True)
            embed.add_field(name="ats", value="fw`", inline=True)
            embed.add_field(name="wf", value="awf", inline=True)
            embed.add_field(name="he", value="wf", inline=True)
            embed.add_field(name="ja", value="ge `(channel)`", inline=True)
            embed.add_field(name="Twitch ", value="gw", inline=True)
            embed.add_field(name="Twitch", value="mhm", inline=True)
            embed.add_field(name="Twitch", value="gww", inline=True)
            embed.add_field(name="Twitch ", value="wgw", inline=True)
            embed.add_field(name="Twitch ii", value="twtw`", inline=True)
            embed.set_footer(text="Made by Flame 'Em -_-rormommemm-_-#4779")
            await ctx.send(embed=embed)
        else:
            await ctx.message.delete()
#

can someone help me the bot is not working

#

at all

#

I made a whole new bot with a ping pong command

slate swan
slate swan
sick birch
slate swan
#
token = "no"
prefix = "!"
import discord
from discord.ext import commands
import requests
import json


bot = commands.Bot(command_prefix=prefix)
bot.remove_command('help')


@bot.event
async def on_ready():
    print("Bot is ready")
    await bot.change_presence(activity=discord.Game(name="Bot prefix: !"))




@bot.command()
async def help(ctx):
    if ctx.channel.type != discord.ChannelType.private:
        if ctx.channel.id == 973394572627562506:
            embed=discord.Embed(title="Help", description=".", color=0x71368A)
            embed.set_thumbnail(url=ctx.guild.icon_url)
            embed.add_field(name="tt", value="tt", inline=True)
            embed.add_field(name="ats", value="fw`", inline=True)
            embed.add_field(name="wf", value="awf", inline=True)
            embed.add_field(name="he", value="wf", inline=True)
            embed.add_field(name="ja", value="ge `(channel)`", inline=True)
            embed.add_field(name="Twitch ", value="gw", inline=True)
            embed.add_field(name="Twitch", value="mhm", inline=True)
            embed.add_field(name="Twitch", value="gww", inline=True)
            embed.add_field(name="Twitch ", value="wgw", inline=True)
            embed.add_field(name="Twitch ii", value="twtw`", inline=True)
            embed.set_footer(text="Made by Flame 'Em -_-rormommemm-_-#4779")
            await ctx.send(embed=embed)
        else:
            await ctx.message.delete()

bot.run(token)
sick birch
#

You know I think you could really simplify this with a dict

slate swan
#

Can you help me fix it

sick birch
#

Without any traceback or knowing what the issue is, no

slate swan
slate swan
sick birch
slate swan
rapid knoll
#

how do you get bots to give users roles that the user cant chose

sick birch
rapid knoll
pure crypt
#

can someone tell me how to make commands like a kick command?

pure crypt
#

@bot.command() doesn’t work

slate swan
#

Same dude

maiden fable
unkempt canyonBOT
#

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

Kicks a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`kick_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.kick_members "discord.Permissions.kick_members") permission to
do this.
rapid knoll
#

How do I fix this

@bot.command()
@commands.has_permissions(ban_members=True)
async def giverole(ctx, member.mention, *, role:discord.Role):
    await member.add_roles('Spectors Journey')
pure crypt
#

i get an error if i made it like this

sick birch
#

It has to be name: typehint format

#

member: discord.Member

rapid knoll
slate swan
sick birch
#

Actually nvm

#

Misunderstood

#

Use that to get the user who should be getting the role

rapid knoll
#

so would I just

discord.Member = ctx.author
pure crypt
#

@bot.command()                                                        
 ^IndentationError: unindent does not match any outer indentation level

#

how can i fix it

rapid knoll
pure crypt
#

!

#

i didn’t change it yet

sick birch
#

Should be using commands extension

rapid knoll
sick birch
#

An extension to handle commands

#

It’s recommended to use that for commands like yours

pure crypt
rapid knoll
pure crypt
#

tasks

small raven
#

@sick birch what is that and how do I fix it

rapid knoll
vale wing
#

Quickstart or smth

sick birch
#

Read the docs, not the YouTube tutorials

austere gust
sick birch
#

I’m not sure why any tutorial would recommend using on message for commands

rapid knoll
#

@sick birch
how do I get the user of the message to used ?

@bot.command()
@commands.has_permissions(ban_members=True)
async def giverole(ctx, member: ctx.author, *, role:discord.Role):
  await member.add_roles('Spectors Journey')
boreal ravine
#

Most tutorials are like that though (d.js, jda)

#

but d.py has a commands extension so good point

sick birch
#

yeah dpy is much more high level it seems

#

Especially djs is a lot more lower level and closed to the API

#

It’s a “true wrapper” you could say, while dpy is more of a framework

slate swan
sick birch
rapid knoll
sick birch
#

Have you learned how to use typehints?

austere gust
sick birch
#

Typehints power Dpy’s commands extension, so knowing how they work is paramount

rapid knoll
sick birch
#

Well @austere gust gave you the answer but I’d strongly suggest learning how to use them so you don’t make things harder for yourself

rapid knoll
sick birch
#

What?

austere gust
sick birch
#

I’m guessing you deleted the message before adding a reaction to it

small raven
elfin island
#

i think what hunter said there is the issue, the bot deletes the message it sends immedietely

slate swan
unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

sick birch
#

hmph

austere gust
slate swan
#

@austere gust i guess it's something wrong with your variable, try changing the name of the variable

heady sluice
elfin island
#

just check if the message author is your bot, and if so don't delete it

heady sluice
#

anand gib me reaction permissions too

elfin island
#

i don't have the power to do that

austere gust
#
    return```
heady sluice
#

sadge

austere gust
#

This?

dapper cobalt
heady sluice
heady sluice
#

to the very start

slate swan
#

guess i got ignored 😦

small raven
austere gust
dapper cobalt
#
msg = await message.channel.send(..)
heady sluice
#

cuz it just doesn't make sense what you both said vemv

austere gust
sick birch
slate swan
small raven
sick birch
#

Reading the documentation is the best way to start

austere gust
sick birch
# small raven

Not sure why it’s doing that but if you go on the documentation you’ll find it

elfin island
#

yeah

#

the module itself doesn't have a symbol on the docs so the docs command can't fetch it i guess

placid skiff
elfin island
#

i don't think the people helping you here appreciate that attitude though :p

placid skiff
heady sluice
#

I'm gonna put on a cap for this one

sick birch
placid skiff
#

Always do that LMAO

sick birch
#

I totally understand that docs can be intimidating first but we can ease that by pointing them in the right direction

heady sluice
#

sad part is the docs won't help unless the person knows oop

placid skiff
#

Nah not totally d.py and related forks docs are the best one i've ever readed

sick birch
#

That’s a bit of an unpopular opinion among the discord bot community

elfin island
#

imo the dpy docs are really good once you figure out how to properly navigate it. if it's your first time on the page it'll look like a massive dump of data and you won't know what to search for in the first place

placid skiff
#

of course you need something to start with
if, for example, you take the examples written in the d.py or other forks github and search in the docs the methods that you don't understand it will be quite simple to learn those package

small raven
placid skiff
#

and to learn how to navigate through the docs

elfin island
slate swan
#

and its a method

elfin island
#

that too ^

slate swan
#

!e

test_str = "uwu"
if test_str.startswith("uwu"):
  print("totally uwu")
unkempt canyonBOT
#

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

totally uwu
small raven
slate swan
#

hunter dont comment on my example

small raven
maiden fable
#
test_str = "uwu"
if test_str.split()[0] == "uwu":
  print("totally uwu")

Ezzz

elfin island
#

message.content.startswith("whatever")

slate swan
#

why even use split when startswith exists (for that case)

maiden fable
#

Thanks

placid skiff
maiden fable
maiden fable
slate swan
#

good to see hunter didnt ew uwu

#

nor blvck

maiden fable
#

I am just ignoring it now since u r never gonna stop saying that

placid skiff
#

u neither... slicing is this lst[x:y:z]

maiden fable
#

I didn't want to slice tho 😐

paper sluice
#

r'^(uwu)' 😳

maiden fable
#

I am using split and comparing the first element of the list

maiden fable
#

content

paper sluice
#

isn't that a webhook?

elfin island
#

you mistyped content

placid skiff
#

and i'm searching if the string i want is in the first characters of the length of that string into another string D_D

paper sluice
#

just send multiple embeds, those are two diff embeds not the same ones

slate swan
#

👋

paper sluice
#

👋

slate swan
#

and I suggest using commands

paper sluice
#

whats different in that field? its normal

placid skiff
#

don't spoiler ashley, he is learning D_D

paper sluice
#

pithink what are you takin' bout

placid skiff
stone beacon
#

That is two different embeds

#

You can see the separation

#

You can even see the timestamp is for a second msg

heady sluice
#

ew

maiden fable
#

same

slate swan
heady sluice
#

no

stone beacon
#

oh man next time I see uwu imma go donate my eyes to a machine learning algorithm

maiden fable
#

How cringe can u even be @slate swan

slate swan
#

Ye that's cringe

#

Cringeee

rapid knoll
#

How do I fix this

@bot.command()
async def join_spectors(ctx, member: discord.Member):
  role_id = 'Spectors Journey'
  msg = f'{member} has joined {member.add_roles(discord.Member, role_id, True)}'
  await ctx.reply(msg)
maiden fable
#

Okay lets stop it now haha

rapid knoll
slate swan
#

Nvmd

sick birch
maiden fable
#

That

stone beacon
#

Yall think if there was an example usecase for every single function on the docs it would help ppl?

sick birch
#

Probably not

placid skiff
#

so add_roles returns the role that was added? D_D

sick birch
#

it's also way too much work

stone beacon
#

Sometimes I feel like the more info we get the harder it is to think for ourselves and we get confused when the time comes to implement something different from what we saw

stone beacon
sick birch
#

discord.py also mentions that it's not a library intended for beginners, so having examples for every usecase would go against that

#

Having some amount of knowledge can greatly help you when making discord bots w/ discord.py

stone beacon
#

That's true but that warning doesn't really prevent much these days

maiden fable
#

I back u

keen silo
#

guy i want help....
I'm currently using discord-slash..now i wanna tottaly uninstall discord-slash and i wanna install pycord and want it to work....idk how to do it

rapid knoll
maiden fable
sick birch
stone beacon
sick birch
tropic burrow
#

when i use nextcord for discord bot, it gives me
RuntimeError: Event loop is closed

stone beacon
#

is your bot token correct?

sick birch
#

Click on the little cog to the right of your name on the bottom left hand corner, then "Advanced", then "Enable developer mode"

tropic burrow
stone beacon
#

Send the entire traceback

maiden fable
#

and remove any token(s) from it ^

stone beacon
#

^^

tropic burrow
#
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\a\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
    self._check_closed()
  File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```


username is deleted
sick birch
#

That doesn't seem like the full traceback because everything there is part of the library's internals

#

Usually when your traceback gives code pointing to the library's internals it's caused by something in your code

tropic burrow
#

it shows this traceback when i run it

sick birch
#

You're 100% sure that's everything in your terminal?

tropic burrow
#

let me recheck

#

i missed this: Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001C07FDEE440>

placid skiff
stone beacon
#

Send ur code fam

sick birch
tropic burrow
#
import nextcord
from nextcord import Interaction
from nextcord.ext import commands


testingServerId = N/A


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

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

@client.event
async def on_ready():
    print("The bot is now ready to be used")

@nextcord.slash_command(name = "hello", description="Replies with hello")
async def hellocommand(interaction: Interaction):
    await interaction.response.send_message("Hello")

client.run('N/A')

/hello basic command
N/A means im not telling you

rapid knoll
#

@sick birch is the member.add_roles correct

@bot.command()
async def join_spectors(ctx, member: discord.Member):
  role_id = '973960685413343253'
  msg = f'{member} has joined {member.add_roles(discord.Member, role_id, True)}'
  await ctx.reply(msg)
stone beacon
#

Is your internet alright?

slate swan
#

ok so i have this code to uh set log channels for different servers

    with open('logchannel.json', 'r') as f:
        logchannels = json.load(f)
    return logchannels[str(message.guild.id)]
@bot.command()
async def setthelogchannel(ctx, logchannel):
    with open('logchannel.json', 'r') as f:
        logchannels = json.load(f)

    logchannels[str(ctx.guild.id)] = logchannel

    with open('logchannel.json', 'w') as f:
        json.dump(logchannels, f)
    await ctx.send(f"Changed the logchannel to {logchannel}")```


and when i set it in a event :
```@bot.event
async def on_message_delete(message):
    embed = discord.Embed(title=f"deleted message!")
    embed.add_field(name= message.content,value=f"Deleted Message: {message.content} by {message.author} ", inline=True)
    logchanneld = bot.get_channel(int(logchannel))
    await logchanneld.send(embed=embed)```

 the issue is i can not call it in the event
logchannel
and i cant use it as a global variable because it's set as a parameter under the def function already
sick birch
#

member.add_roles(discord.Member, role_id, True) is incorrect

stone beacon
rapid knoll
sick birch
#

!d discord.Member.add_roles @rapid knoll

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to
use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list
of roles than the highest role of the member.
tropic burrow
tropic burrow
sick birch
#

May just be a bug with nextcord then

#

Usually that specific error happens with an incorrect bot token

tropic burrow
#

should i make a variable for it and regenerate the token

maiden fable
#

@tropic burrow what is yr nextcord version

#

!pypi nextcord

unkempt canyonBOT
maiden fable
#

this one?

tropic burrow
#

ah shit no

slate swan
#

..

tropic burrow
#

1.8 something

slim whale
maiden fable
#

There u go

#

That can fix the issue

tropic burrow
#

let me check again what do i type in the terminal to check version again (vs code terminal)

maiden fable
#

pip show nextcord

keen silo
#

Code:
`import discord
from discord.ext import commands

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

@bot.slash_command()
async def hello(ctx, name: str = None):
name = name or ctx.author.name
await ctx.respond(f"Hello {name}!")`

Error:
Traceback (most recent call last): File "d:\Kunnu\Discord.py\LF Test\bot.py", line 7, in <module> @bot.slash_command() AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?

maiden fable
#

u need to install from github

keen silo
tropic burrow
# maiden fable `pip show nextcord`

i get this ```pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1

  • pip show nextcord
  •   + CategoryInfo          : ObjectNotFound: (pip:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException```
maiden fable
#

pip install git+https://github.com/Rapptz/discord.py.git

keen silo
rapid knoll
#

giving bots permissions is it at:get_permissions() at = @

tropic burrow
#

ok the version is correct i am a idiot

keen silo
tropic burrow
#

then what is wrong

slate swan
keen silo
slate swan
#

uh

#

It's different

tropic burrow
#

im using nextcor

rapid knoll
#

what does RuntimeWarning: Enable tracemalloc to get the object allocation traceback mean

tropic burrow
#

d

slate swan
tropic burrow
#

gives me same error

slate swan
#

...

boreal ravine
tropic burrow
#

ill resend everything jere

paper sluice
slate swan
boreal ravine
#

oh

tropic burrow
#
import nextcord
from nextcord import Interaction
from nextcord.ext import commands


testingServerId = N/A


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

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

@client.event
async def on_ready():
    print("The bot is now ready to be used")

@nextcord.slash_command(name = "hello", description="Replies with hello")
async def hellocommand(interaction: Interaction):
    await interaction.response.send_message("Hello")

client.run('N/A')```

Error: Runtime Error: Event loop is closed
slate swan
#

Bruh

boreal ravine
#

that's not an error, it's a warning

tropic burrow
#

but nothing prints

boreal ravine
#

show the error above that warning

tropic burrow
#

the traceback?

slate swan
#

Yes

boreal ravine
#

yes

#

Full one if you can

slate swan
#

!paste if big

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
#

#bot-commands @rapid knoll

tropic burrow
#
  File "C:\Users\censored\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
  File "C:\Users\censored\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
  File "C:\Users\censored\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
  File "C:\Users\censored\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed```

my user will be censored
slate swan
#

How can my bot see when someone upvoted on discordbots.com?
And then start a 12 Hour timer?

#

ok so i have this code to uh set log channels for different servers

def setlogchannel(bot, message):
    with open('logchannel.json', 'r') as f:
        logchannels = json.load(f)
    return logchannels[str(message.guild.id)]
@bot.command()
async def setthelogchannel(ctx, logchannel):
    with open('logchannel.json', 'r') as f:
        logchannels = json.load(f)

    logchannels[str(ctx.guild.id)] = logchannel

    with open('logchannel.json', 'w') as f:
        json.dump(logchannels, f)
    await ctx.send(f"Changed the logchannel to {logchannel}")```



and when i set it in a event :
```@bot.event
async def on_message_delete(message):
    embed = discord.Embed(title=f"deleted message!")
    embed.add_field(name= message.content,value=f"Deleted Message: {message.content} by {message.author} ", inline=True)
    logchanneld = bot.get_channel(int(logchannel))
    await logchanneld.send(embed=embed)```


 the issue is i can not call it in the event
logchannel
and i cant use it as a global variable because it's set as a parameter under the def function already
ebon island
#

What is the best date/time package in Python?

maiden fable
#

humanize?

stone beacon
#

I'd say datetime

#

Pendulum is nice also

#

But still datetime is easy to use and it's in the standard lib

regal pulsar
#

lol

slate swan
#

Lol

ebon island
#

Haha was just wondering if there are any others worth knowing, thanks all 🙂

slate swan
#

!d datetime

unkempt canyonBOT
#

Source code: Lib/datetime.py

The datetime module supplies classes for manipulating dates and times.

While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.

alpine cove
pale saddle
#

please tell me which discord bot to use for the host, telegram bot?

tropic burrow
#

so i tried something else

import discord

TOKEN = "[REDACTED]"

client = discord.client()

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

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    
    elif message.content.startswith("!hello") or message.content.startswith("/hello"):
        await message.channel.send("Hello Pyramid Finder!")


client.run(TOKEN)

error is client = discord.client() TypeError: 'module' object is not callable

paper sluice
#

its Client not client

#

!d discord.Client

unkempt canyonBOT
#

class discord.Client(*, intents, **options)```
Represents a client connection that connects to Discord.
This class is used to interact with the Discord WebSocket and API.

A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
slate swan
#
  def setlogchannel(bot, message):
    with open('logchannel.json', 'r') as f:
        logchannels = json.load(f)
    return logchannels[str(message.guild.id)]
@bot.command()
async def setthelogchannel(ctx, logchannel):
    with open('logchannel.json', 'r') as f:
        logchannels = json.load(f)

    logchannels[str(ctx.guild.id)] = logchannel

    with open('logchannel.json', 'w') as f:
        json.dump(logchannels, f)
    await ctx.send(f"Changed the logchannel to {logchannel}")```

and when i set it in a event :
```py
@bot.event
async def on_message_delete(message):
    embed = discord.Embed(title=f"deleted message!")
    embed.add_field(name= message.content,value=f"Deleted Message: {message.content} by {message.author} ", inline=True)
    logchanneld = bot.get_channel(int(logchannel))
    await logchanneld.send(embed=embed)```
my issue is  :     await logchannel.send(embed = embed)
NameError: name 'logchannel' is not defined
slate swan
paper sluice
slate swan
paper sluice
#

thats a different function

#

...

slate swan
#

ik

#

how can i define it so that it works

paper sluice
#

where do u want to send the deleted message in?

slate swan
#

a log channel that is set in a shit json database?

paper sluice
#

open the json

#

get the id from there

#

and then send the message to that channel

heady sluice
slate swan
#

dude the thing is im designing this to be a example of a public bot with log channel database so that i don't have to set a actual id everytime someone sets a log channel

heady sluice
#

wait no ew

paper sluice
slate swan
supple plume
#

is there an event for when a command is ran?

paper sluice
slate swan
#

no the thing is i set logchannel as the id it sends to the json file and im trying to use it as a parameter for the channel that the log is going to be sent to however it seems it doesn't work

slate swan
stone beacon
slate swan
paper sluice
#

example of what u can do

{<guild_id>:
{"log_channel_id": 128372913} // lets say this is the default id
}
@bot.command()
async def setthelogchannel(ctx, logchannel):
    with open('logchannel.json', 'r') as f:
        logchannels = json.load(f)
    logchannels[ctx.guild.id]['log_channel_id'] = logchannel
 with open('logchannel.json', 'w') as f:
        json.dump(logchannels, f)
...
toxic thicket
#
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def пред(ctx, member: discord.Member = None, *, reason = None):
    
    cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
    base.commit()
    
    
    if member is None:
        await ctx.send("Выберите участника")
        return
    
    if reason is None:
    	await ctx.send("Укажите причину")
    	return
        
        
    warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ? AND guild_id = ?", (member.id,ctx.guild.id)).fetchone()
    
    print(1)
    cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,reason))
    base.commit()
    print(2)
    cursor.execute(f'UPDATE warning SET warn = warn + 1 WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
    base.commit()
    print(3)
    await ctx.send(f"**{ctx.author.name}** Выдал предупреждение #{warnings[2]} {member} (случай # ) {reason}") 

If a person has no warnings, then when you give out, the bot does not write anything to the chat, but he issued a warning, if you issue it again, the bot will already write, how to fix it?

slate swan
paper sluice
#

then.... where r u gonna send the message?

slate swan
#

ignore that for now, ur code has errors

paper sluice
#

🤷‍♂️

slate swan
#

ok just few issues fixed

#

but u still did not actually fix the main issue, logchannel is not defined under on_delete event

paper sluice
#

well because... ur not taking the id from the json

#

ur just storing it and not using it? why?

tropic burrow
#
import discord
import os
import requests
import json

TOKEN = "N/A"

client = discord.Client()

def get_joke():
    response = requests.get
    ("https://api.icndb.com/random")
    json_data = json.loads(response.text)
    joke = json_data[0]['q'] + " -" + json_data[0]['a']
    return joke

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

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    
    elif message.content.startswith("!hello") or message.content.startswith("/hello"):
        await message.channel.send("Hello Pyramid Finder!")
    elif message.content.startswith("/joke") or message.content.startswith("?joke"):
        joke = get_joke()
        await message.channel.send(joke)

client.run(TOKEN)```


So no jokes happen why?
slate swan
tropic burrow
#

bot

slate swan
#

change client to bot

#
import discord
import os
import requests
from discord.ext import commands
import json

TOKEN = "N/A"

bot = commands.Bot(command_prefix= "your prefix")

def get_joke():


    response = requests.get
    ("https://api.icndb.com/random")
    json_data = json.loads(response.text)
    joke = json_data[0]['q'] + " -" + json_data[0]['a']
    return joke

@bot.event
async def on_ready():
    print(f"{0.user} is online1".format(bot))

@bot.event

async def on_message(message):
    if message.author == bot.user:
        return
    
    elif message.content.startswith("!hello") or message.content.startswith("/hello"):
        await message.channel.send("Hello Pyramid Finder!")
    elif message.content.startswith("/joke") or message.content.startswith("?joke"):
        joke = get_joke()
        await message.channel.send(joke)

bot.run(TOKEN)```
tropic burrow
#

wait

#

im getting errors wen i say /joke

dull terrace
#

Can anyone write me code that will make me more patient waiting for top.gg to approve my bot froggy_chill

slate swan
tropic burrow
#

oh.. the respons.text

sick birch
#

You can just send it as a regular message

#

Get the channel, send it

#

Just like regular

#

As if this was a regular non slash command

restive rampart
restive rampart
#

Well you still won't reply

#

Defer only gives you more time to reply if i'm correct, but if you send a message in the channel instead of replying then it's useless

sage otter
#

Bot isn’t part of the discord namespace

#

It’s inside ext.commands

#

You changed the variable to Bot but didn’t event change everywhere where it’s supposed to be referenced

restive rampart
slate swan
#

it is

heady sluice
#

I can't say it any nicer

sick birch
rare saddle
#

How to make a check so that bots, in principle, cannot be added to the black list, in the screenshot, only the bot executing the command cannot be added to the black list

heady sluice
#

elif member.bot?

restive rampart
heady sluice
#

member.bot is true if the member is a bot account

rare saddle
slate swan
heady sluice
#

I saw the client code before and it was much better

wispy parrot
#

Yep it was

slate swan
#

because according to my small brain client does not work for bots

heady sluice
#
  1. you didn't replace it everywhere
  2. a Bot instance is coming from discord.ext.commands and requires a command_prefix kwarg passed to it
  3. you didn't follow pep8 while making the Bot instance and capitalized it
  4. you did want to replace the Client instance with a Bot instance and tried to do so, but didn't use the pros of having a bot and continued to work with on_message, still using more memory because of the Bot instance
#

you could've also told him to use aiohttp instead of requests

slate swan
#

bro is gonna kill me on my second day on discord.py

heady sluice
#

👍🏿

slate swan
#

i'll try fixing it if u want anyways

heady sluice
#

it's okay

#

you don't have to

#

I mean, did Mokiposter get an answer?

uncut portal
#

python doesn't care if you follow pep8 or not

heady sluice
#

k but I do and it's good practice 😔

uncut portal
#

sure, and it always is

ebon island
#

Best to learn best practices

slate swan
#

ok check now hope its better

heady sluice
#

I'm starting to like it, you made a slight mistake in on_ready and on_message

#

because you used Bot instead of bot which is undefined

slate swan
#

ok fixed

heady sluice
#

it's now not worse than the original was

rare saddle
#

Why when I put the bot on the hosting, it is displayed as None and how to make it so that my nickname and ID are displayed?

slate swan
#

i'll keep wondering until i sleep what i did wrong

#

maybe i just have low iq for python lol

heady sluice
#

or you're new

#

and jumped into an ocean with sharks without learning to swim

slate swan
#

maybe tell me whats wrong so i can get some more info

heady sluice
#

little things like f-strings

#

big things like using commands instead of on_message

slate swan
#

thats his code shrug , ik there's some shit there but i honestly just bothered fixing the main issue that his bot doesn't respond or something like that

uncut portal
#

thats the problem with python discord bot APIs tbh. Being something that is seemingly a fun project for a beginner and being in a language like python that targets all experience levels of the programming world you can get quite a large divide is the abilities of the users and hence APIs like discord.py and it's derivatives are very sophisticated however they really expect you to know python and it's intricacies. Something you will see a lot is beginners writing all of these subclasses and using all of these decorators without ever learning how or why they work, or why we need to put await before some functions and the idea of blocking

tl;dr if you are new to python and are finding discord bots hard don't worry about it, they can be hard

dull terrace
#

Prolly worth mentioning that bots are actually not that difficult to write, you can do on message and all that stuff and it'll pretty much work perfectly fine

heady sluice
#

it's a good starter project if you actually try to find out why and how those things you write work, otherwise you just write stuff, but never get to a higher level of doing more and more advanced projects

#

or being able to

slate swan
#

@tropic burrow

    response = requests.get("https://api.icndb.com/random")
    json_data = json.loads(response.text)
    joke = json_data[0]['q'] + " -" + json_data[0]['a']
    return joke```
```py
@bot.command()
async def joke(ctx):
    await ctx.send(get_joke())
#

kind of better

heady sluice
#

mmmmmmmmm

#
@bot.command()
async def joke(ctx):
    await ctx.send(get_joke())
dull terrace
#

Isn't there an attribute specifically for bots

#

Like message.author.bot

heady sluice
#

discord.Member.bot

slate swan
#

or api dead

heady sluice
#

I think that second option is a bit unrealistic

#

might it be in his get_joke?

#

!d json.loads

unkempt canyonBOT
#

json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *s* (a [`str`](https://docs.python.org/3/library/stdtypes.html#str "str"), [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") or [`bytearray`](https://docs.python.org/3/library/stdtypes.html#bytearray "bytearray")
instance containing a JSON document) to a Python object using this
[conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).

The other arguments have the same meaning as in [`load()`](https://docs.python.org/3/library/json.html#json.load "json.load").

If the data being deserialized is not a valid JSON document, a
[`JSONDecodeError`](https://docs.python.org/3/library/json.html#json.JSONDecodeError "json.JSONDecodeError") will be raised...
heady sluice
#

dunno

scarlet aurora
#

hello

slate swan
#

@heady sluice

import aiohttp

@bot.command()
async def joke(ctx):
       async with aiohttp.ClientSession() as session:
        request = await session.get('https://api.icndb.com/random')
        jokejson = await request.json()
        await ctx.send(jokejson)```
#

his api is just dead

#

wdym and the code can be shorter

slate swan
#

wdym it doesnt respond

#

did you check the status code if any?

#

yep his api is bad

#

bro

#

youre trying to view the endpoint

#

with your browser

heady sluice
honest laurel
#

How would discord.ext.tasks work with multiple bot instances? If i'm not mistaken there's nothing synchronizing these

heady sluice
#

you don't use multiple bot instances

honest laurel
heady sluice
#

you can only run one too

heady sluice
honest laurel
#

Ehm, why we have auto sharded bot then? 🙂

heady sluice
#

that's one instance

#

and we have it so we don't need multiple bot instances

honest laurel
#

I see, how do you scale it past single physical node then?

heady sluice
#

please rephrase

honest laurel
#

If you run into some kind of bottleneck how would you scale past one server (physical server where you run your bot)

heady sluice
#

I'll try to get a more comprehensive person for u

#

@slate swan u

honest laurel
#

I probably won't run into such problems but i'm still curious how would you do that 🤔

slate swan
heady sluice
#

I don't know

slate swan
#

ive never worked with tasks lol

heady sluice
#

I see

honest laurel
slate swan
#

hi

honest laurel
#

It's not really related to tasks, just trying to figure out how would you scale your bot past single process or server (not discord server)

heady sluice
#

we're bottlenecking server past one, you haven't worked with tasks yet so we're all numb

slate swan
#

or just the process of scaling your bots into servers?

honest laurel
slate swan
heady sluice
#

so two different scripts for two different bots

#

?

honest laurel
#

It's not related to hosting 🤔

honest laurel
slate swan
#

you mean shards😭

heady sluice
#

yeah shards run on one process

slate swan
#

im so confused😭

honest laurel
#

AutoShardedBot just acquires more connections, if you run into some kind of cpu bottleneck you'd need more processes

heady sluice
#

he's french

#

he's using embouteillage

#

I'm starting to lose all my unconfusion

slate swan
heady sluice
#

Doctor you're asking two people dumber than u

heady sluice
#

but using shards on more processes are even weird to think about

slate swan
heady sluice
#

and which all of them

#

Robin

sick birch
slate swan
heady sluice
#

well that's not what I was counting on when I saw Robin typing

slate swan
#

maybe ill eat him😋

honest laurel
#

I guess you can manually setup shard ids for each bot instance

heady sluice
#

😔

sick birch
heady sluice
#

I think you're fine unless you do

honest laurel
slate swan
sick birch
#

Nothing wrong with wanting to know

heady sluice
sick birch
#

Heck I’ve wanted to do my own autoshardedbot just because

#

Never gotten around to doing it tbh

slate swan
#

😩

scarlet aurora
slate swan
frozen patio
#

XD

#

Dead chat

paper sluice
#

u need to put f before the string like f'...'

#

ya

small raven
#

ty

lucid vine
#
  File "c:\Users\Yuki\Desktop\KyuuMainPy\discord-music\main.py", line 63, in <module>
    bot = MusicBot(command_prefix=PREFIX, intents=intents)
  File "c:\Users\Yuki\Desktop\KyuuMainPy\discord-music\main.py", line 27, in __init__
    self.loop.create_task(self.start_nodes())
  File "C:\Python310\lib\site-packages\discord\client.py", line 110, in __getattr__
    raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000180AB95B9D0>``` dpy 2.0
#
import os
import wavelink
from discord.ext import commands
from discord import Intents
from essentials.player import WebPlayer
from dotenv import load_dotenv
import pathlib
import sys

load_dotenv(".env")

os.environ["JISHAKU_NO_DM_TRACEBACK"] = "true"


class MusicBot(commands.AutoShardedBot):
    def __init__(self, command_prefix, **options):
        super().__init__(command_prefix, **options)

        self.can_function = False
        self.error_message = (
            "Bot is not ready to listen your commands. Please try after a few moments."
        )

        if not hasattr(self, "wavelink"):
            self.wavelink = wavelink.Client(bot=self)

        self.loop.create_task(self.start_nodes())

    async def on_message(self, message):
        await self.process_commands(message)

    async def on_ready(self):
        print(f"{self.user} is ready to play musics")

    async def start_nodes(self):
        await self.wait_until_ready()

        await self.wavelink.initiate_node(
            host="",
            port=,
            rest_uri="",
            password="",
            identifier="",
            region="",
        )

        for guild in self.guilds:
            if guild.me.voice:
                player: WebPlayer = self.wavelink.get_player(guild.id, cls=WebPlayer)
                try:
                    await player.connect(guild.me.voice.channel.id)
                    print(f"Connected to existing voice -> {guild.me.voice.channel.id}")
                except Exception as e:
                    print(e)

        self.can_function = True


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

PREFIX = os.getenv("PREFIX")
bot = MusicBot(command_prefix=PREFIX, intents=intents)

@bot.event
async def setup_hook():
    for file in sorted(pathlib.Path("cogs").glob("**/[!_]*.py")):
        ext = ".".join(file.parts).removesuffix(".py")
        try:
            await bot.load_extension(ext)
        except Exception:
            print(f"Failed to load extension: {ext}", file=sys.stderr)

@bot.command()
@commands.is_owner()
async def reload(ctx, extension):
    await bot.unload_extension(f'cogs.{extension}')
    await ctx.send(f"unloaded {extension}")
    await bot.load_extension(f'cogs.{extension}')
    await ctx.send(f"loaded {extension}")

@bot.command()
@commands.is_owner()
async def unload(ctx, extension):
    await bot.unload_extension(f'cogs.{extension}')
    await ctx.send(f"unloaded {extension}")

@bot.command()
@commands.is_owner()
async def load(ctx, extension):
    await bot.load_extension(f'cogs.{extension}')
    await ctx.send(f"loaded {extension}")


TOKEN = os.getenv("TOKEN")
bot.run(TOKEN)```
paper sluice
keen mural
#

how would these both go in the same if statement

sick birch
paper sluice
sick birch
keen mural
#

thx 😄

lucid vine
sick birch
#

How would it endwith both?

paper sluice
sick birch
#

you’re looking for the or operator

sick birch
paper sluice
keen mural
# sick birch It can’t

ok, could i make it so if i have a command test for example, and i wanna make it so if they do .test max or .test all it would send the same response how would i do that in one if statement

paper sluice
#

are you using on_message?

keen mural
#

no

sick birch
#

But you should probably do this with a command

keen mural
#

@client.command

tawdry plover
#

As I'm trying to get my bot token, it just says "Reset Token." Can anyone help out.

paper sluice
#
@client.command()
async def test(ctx, arg):
    if arg in ('max', 'all'):
      ...
keen mural
#

to generate a new one since it gets hidden after time

keen mural
#

and i can do if arg==None then my regular command

tawdry plover
sick birch
tawdry plover
#

and my 2fa code is apparently invalid.

#

like what.

#

Do we need to keep the -

#

or no?

sick birch
#

The what?

tawdry plover
#

in the 2fa code..

#

So how would I get my token then..

#

Reset it?

sick birch
#

Yes?

tawdry plover
#

mk.

sick birch
#

You should have a 2fa app on your phone

tawdry plover
#

What...

sick birch
#

Either that or use your backup codes

tawdry plover
#

What's the app called?

sick birch
#

I use google Authenticator

tawdry plover
#

mk.

sick birch
#

If you lost your backup codes that’s a big issue

tawdry plover
#

"Invalid two-factor code"

#

that's all I have.

tawdry plover
unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

tawdry plover
#

bruh

#

wtaf

heady sluice
#

bot variables

#

like in the tag

paper sluice
heady sluice
paper sluice
heady sluice
#

you attach a variable to your bot so you can change it everywhere

#

even in other files

heady sluice
paper sluice
#

ur time thing

heady sluice
#

oh it's the ending

#

yeah Hungarian makes the words have other meanings with every single ending possible

paper sluice
#

0.o

heady sluice
#

so -kor is like at

#

at 21:52

paper sluice
#

ah cool

stiff gorge
#
    @commands.command()
    async def imagify(ctx, url: Union[discord.Member, str], size: int = 14):
      if not isinstance(url, str):
        url = url.display_avatar.url
        def get_emojified_image():
          r = requests.get(url, stream=True)
          image = Image.open(r.raw).convert("RGB")
          res = emojify_image(image, size)
          if size > 14:
            res = f"```{res}```"
            return res
            result = bot.loop.run_in_executor(None, get_emojified_image)
            await ctx.send(result)

File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 919, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.image' raised an error: SyntaxError: 'await' outside async function (image.py, line 40)

heady sluice
#

discord messed it up

paper sluice
#

ur awating in get_emojified_image which is a sync function

heady sluice
#

it's a sync function, make it async

#

😭

paper sluice
#

why do u need two functions though?

#

and why r u using requests with discord bot lemon_angrysad

heady sluice
#

pointn't

#

anyways, after return nothing will launch

brave forge
#

how can I make data from one command be transferred to another ??
how to create this variable?

paper sluice
#

bot.variable = ...

heady sluice
#

you can create it anywhere and it's like any other variable

#

you just attach it to bot

#

like Ryuga

heady sluice
#

please code

#

you used stat before you assigned anything to it

#

maybe self.bot.variable = message?

brave forge
#

@heady sluice and now in order for me to transfer this variable to another command, I need to write "self.bot.variable = stat" or just "stats"

heady sluice
#

it doesn't matter what you set to it

#
    @commands.command(aliases = ['status', 'Status', 'статус', 'Статус'])
    @commands.has_permissions(administrator = True)
    async def __stats__(self, ctx, *, message):
        stat = message
        self.bot.variable = stat
        embed = discord.Embed(description= f'Вы установили статус {stat}', colour=0xF1C40F)
        await ctx.send(embed=embed)
```you could use this
#

or spare yourself a variable

#
    @commands.command(aliases = ['status', 'Status', 'статус', 'Статус'])
    @commands.has_permissions(administrator = True)
    async def __stats__(self, ctx, *, stat):
        self.bot.variable = stat
        embed = discord.Embed(description= f'Вы установили статус {stat}', colour=0xF1C40F)
        await ctx.send(embed=embed)
brave forge
distant river
#

I'm trying to run this simple bot:

from discord.ext import commands
from secret import Secret
client = commands.Bot(command_prefix='.')
@client.event
async def on_ready():
    print("Bot is Ready.")
#
# @client.event
# async def on_member_join(member):
#     print(f'{member} has joined.')
#
#
# @client.event
# async def on_member_remove(member):
#     print(f'{member} has left a server.')

@client.command()
async def add(ctx, num1: int, num2: int):
    await ctx.reply(num1+num2)
client.run(Secret.bot_token)

My bot shows up in discord channel, but I couldn't run the /add command or it's not in the command list.

heady sluice
#

yes, it doesn't matter what's after the =
it will be transferred and as I see, stat = message

#

you do you

heady sluice
distant river
#

could someone help me debug?

heady sluice
#

you type .add in the channel

distant river
#

oh not slash

heady sluice
#

no

#

slashes are completely different

distant river
#

I tried this: Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "add(3,4)" is not found

heady sluice
#

you use it like
.add 3 4

distant river
#

oh

heady sluice
distant river
#

let me check

#

the slash command is pretty nice, do you know which repo/library I can use for slash command?

heady sluice
#

all of the dpy forks include slash commands I think

#

and dpy 2.0 too

#

you can use self.bot.variable in another command

distant river
#

thanks, I'll look into that 😄

heady sluice
brave forge
distant river
heady sluice
#

you can do anything with it, easiest to try is

@commands.command()
async def command_b(self, ctx):
    await ctx.send(self.bot.variable)
heady sluice
#

did you use the other command beforehand?

regal pulsar
#

do pip install disnake

heady sluice
#

without restarting the bot?

regal pulsar
#

then control h

heady sluice
regal pulsar
#

replace discord with disnake

regal pulsar
#

LMAO

sick birch
#

??

regal pulsar
#

i saw that

brave forge
#

@sick birch help

heady sluice
#

I asked if you used command A which sets self.bot.variable before command B

sick birch
#

ah just saw it

#

Full traceback?

#

I suspect that's not where the error is pointing

regal pulsar
#

wait are you making an avatar command

brave forge
#

Command raised an exception: AttributeError: 'Bot' object has no attribute 'variable'

regal pulsar
#

you could just do

#
await ctx.channel.send(ctx.author.avatar_url)
regal pulsar
#

what

#

touch your code?

#

i just showed you a way to access the user’s avatar

heady sluice
#

1.7 moment

regal pulsar
#

🐲

#

wow this emoji looks awful on ios

sick birch
#

That still doesn't look like the full traceback, there has to be something above
AttributeError: 'Bot' object has no attribute 'variable'

regal pulsar
#

its a profile c9mmand right

sick birch
#

Unless you have a shoddy error handler that's messing with it

regal pulsar
#

please dont what 💀

#

and you replied to me talking about an emoji lmao

heady sluice
#

don't go off topic

sick birch
#

They don't want you derailing the conversation I'm guessing

regal pulsar
#

ah

heady sluice
#

I'll ignore that

brave forge
heady sluice
#

did you use command A before command B?

regal pulsar
sick birch
brave forge
heady sluice
#

well that's the only way it works

#

or you set self.bot.variable outside of a command

#

but I doubt you'd want to do that

#

so first use command A then command B

brave forge
heady sluice
#

no

#

only runtime matters here

brave forge
#

@heady sluice has
I swapped them and everything works

heady sluice
brave forge
#

@heady sluice I'm in ahuya myself

slate swan
#

can some1 explain me, why my slash command isnt loaded in my server. I use guild_id and when I run the bot, no errors occur

heady sluice
#

how do you sync it

sick birch
#

Not sure if some of the other libraries have a sync command?

heady sluice
#

no

#

dpy is being original

#

me after update

heady sluice
#

that's dpy indeed brainmon

sick birch
#

You are using d.py - make sure to sync

sick birch
heady sluice
#

he's a man of culture

sick birch
#

I like the design pattern when it came to sync

heady sluice
#

oh wait

#

it's
await tree.sync(guild=discord.Object(id=guild_id))
there

#

this is one thing I'd dare put in on_ready

#

it would accidentally keep my stuff up-to-date

sick birch
#

Agreed

#

I was thinking the same thing

heady sluice
#

exploit bugs

sick birch
#

You could still argue it's bad on the grounds that sending an API request on_ready is going to get you kicked off the API

heady sluice
#

and making a task for the exact same thing would be much more practical

sick birch
#

Right, but if you don't really care about syncing it on an interval, setup_hook() works just fine too

heady sluice
#

never used it

brave forge
#

@heady sluice stop, you can also make the team work even if one of the teams was not used

heady sluice
#

what do you mean by teams

#

and why should I stop FeelsBadMan

brave forge
#

@heady sluice
until you write the status command in the prof command, it is written to you that the status is "missing"

heady sluice
#

exactly!

slate swan
heady sluice
#

if you would want to store it somewhere then

#

well... depends, is this something for every user? then I would get a database ||or json||

brave forge
keen mural
#
@commands.cooldown(1, 60, commands.BucketType.user)

@work.error
async def work_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        em = discord.Embed(title=f"**Wait a little bit lmao**",description=f"Try again in `{error.retry_after:.0f}` seconds.", color=discord.Colour.red())
        await ctx.send(embed=em)```
How would i put the cooldown time in minutes?
heady sluice
#
if self.bot.variable:
    #the variable exists
else:
    #it doesn't exist
heady sluice
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")...
heady sluice
#

mmm

heady sluice
#

it's actually the only way to put it in seconds, so
x*60 where x are the minutes would work

keen mural
#

yeah but in the error message

heady sluice
#

or

#

oh there

keen mural
#

how would i make the error message display minutes instead of seconds

heady sluice
#

description=f"Try again in `{error.retry_after:.0f/60}` minutes."

keen mural
brave forge
heady sluice
#

await

#

you forgot await

heady sluice
keen mural
heady sluice
#

!e print(465.5:.0f/60)

unkempt canyonBOT
#

@heady sluice :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     print(465.5:.0f/60)
003 |                  ^
004 | SyntaxError: invalid decimal literal
heady sluice
#

I don't even know how what you did works

keen mural
#

i get that a lot

heady sluice
#

!e print(int(465.5)/60)

unkempt canyonBOT
#

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

7.75
heady sluice
#

description=f"Try again in `{int(error.retry_after)/60}` minutes."

heady sluice
#

how did this become so different so quickly

heady sluice
#

I think you should put new_command_onygo inside the Bot class

slate swan
heady sluice
# keen mural

description=f"Try again in `{int(error.retry_after/60)}` minutes." seems much nicer

#

andy

#

hello

pliant gulch
#

I would suggest a ternary here so you don't get a long floating point number

heady sluice
#

it just cuts off the decimals

heady sluice
#

so int(9.9999999) is equal to 9

pliant gulch
#

!e ```py
print(int(1/60))

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

0
keen mural
#

i could do if

#

statement

heady sluice
#

!e
print(int(1/60) + 1)

unkempt canyonBOT
#

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

1
pliant gulch
#

But the actual cooldown isn't a minute...

heady sluice
keen mural
#

if int(error.retry_after/60) < 1:

#

would that work

heady sluice
#

try again in less than int(1/60) + 1 minute(s)

pliant gulch
#
if retry_after % 60 == 0:
    return retry_after / 60

return round(retry_after)
``` would be what you want
#

Not doing all this int stuff that would show you the wrong time

heady sluice
#

there's a round type??

#

!d round

unkempt canyonBOT
#

round(number[, ndigits])```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.

For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.

For a general Python object `number`, `round` delegates to `number.__round__`.
pliant gulch
#

!e ```py
retry_after = 120
if retry_after % 60 == 0:
print(f"retry in {retry_after / 60} mins")
else:
print(f"retry in {round(retry_after)} seconds")

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

retry in 2.0 mins
pliant gulch
#

!e ```py
retry_after = 100
if retry_after % 60 == 0:
print(f"retry in {retry_after / 60} mins")
else:
print(f"retry in {retry_after} seconds")

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

retry in 100 seconds
pliant gulch
#

modulo operator will check if there is a remainder, in case you were wondering

slate swan
fringe harness
#

Lets say ur creating a bot to return stock info, if u do the the command !stockdata TSLA, it should return the data

#

Or u do !stockdata

#

The bot will ask u for what stock and u input the ticker symbol

sick birch
#

That sounds like a perfect way to use wait_for

fringe harness
#

any videos for this kinda thing

fringe harness
sick birch
#

Why?

slate swan
#

Just a normal question, I host my bot on my PC with Pycharm, will it go offline if I put my pc on Sleep Mode?

sick birch
#

It depends on PC

#

Different PCs go into different ACPI states on sleep

slate swan
#

Well i'm gonna try it and see thanks!

slate swan
sick birch
#

What's copy_global_to?

lucid vine
heady sluice
#

about youtube Terms of Service

lucid vine
#

its not youtube?

heady sluice
#

I wanted to go to bed now I'm back here yert

sick birch
#

Where's the audio from?

heady sluice
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
lucid vine
#

its not ytdl

heady sluice
#

it's wavelink

lucid vine
#

idk why so many people in this server have a broom up their arse for nothing

slate swan
heady sluice
#

behave

lucid vine
#

denial 💀💀💀

heady sluice
#

mhm

sick birch
#

Please keep it civil, we don't appreciate you insulting other members

lucid vine
slate swan
frail notch
#

How can I make my bot do this for each message sent? ```py

q = str(ctx.message.content)
answer = requests.get(f'{API}{q}')
print(answer.json()['cnt'])```because ```py

@client.command()
async def on_message(ctx):
q = str(ctx.message.content)
answer = requests.get(f'{API}{q}')
print(answer.json()['cnt'])``` doesn't work, it just leaved the console without anything.

lucid vine
#

alot of people in this server think they are the discord sheriff

sick birch
#

Not necessarily. None of us want to get banned

heady sluice
#

listen, you do you, but we don't help with projects that break any Terms of Services

lucid vine
sick birch
#

<@&831776746206265384>

lucid vine
#

its not my fault

#

ill just go and do sum rq denial lol

slate swan
#

cringe

lucid vine
#

look at ur name @slate swan

regal pulsar
#

its just not allowed here

lucid vine
regal pulsar
#

cuz reasons

heady sluice
#

it indeed isn't

lucid vine
#

so i dont care

regal pulsar
sick birch
#

Please stop insulting other members

heady sluice
#

does someone really have to be a mod to point someone to the rules

sick birch
#

No indeed

#

We thrive by keeping each other in check 😄

slate swan
lucid vine
#

mister denial come into my dms rq

regal pulsar
#

me?

slate swan
#

can we maybe change the subject and help me thinkmon

lucid vine
#

everything in dms stays in dms apparantly

heady sluice
#

...?

regal pulsar
#

no what i meant was

#

for example, when i first learnt python i made a discord selfbot

#

just for fun

heady sluice
#

stop

regal pulsar
#

but im not gonna ask people for help with that here

hollow badger
# lucid vine so i dont care

Please respect other members. We won't help or encourage use of code that breaches terms of service, as you have been told.

heady sluice
regal pulsar
#

different servers have their own rules

#

you might find a server where you can talk about tos breaking stuff

lucid vine
regal pulsar
#

but that isnt here

sick birch
regal pulsar
lucid vine
#

what nig

regal pulsar
heady sluice
#

the youtube ToS doesn't state ytdl, it states the general download of audio from youtube

sick birch
#

I'm assuming you saw that Grote?

coral flicker
#

ytdl is just an example of a library that uses copyrighted music without a license, using wavelink to do it instead doesn't make it okay.

lucid vine
worldly solstice
#

Hey there!

Any ideas how i could fix this issue where the embed size changes massively depending on how long the name of the seller is?

regal pulsar
#

so me downloading videos for my soundboard was a no no 💀

sick birch
heady sluice
heady sluice
#

from like a bot

regal pulsar
#

nah

lucid vine
worldly solstice
regal pulsar
#

i just wanted a spike defuse sound for some valorant trolling

regal pulsar
coral flicker
regal pulsar
#

oh

#

well my bad 💀

heady sluice
#

oof

sick birch
regal pulsar
#

what he means is

#

we cant help you.

slate swan
#

help please

regal pulsar
slate swan
#

the package used is speedtest-cli(it is the only package we need)

import speedtest
from time import sleep
speed=speedtest.Speedtest()

option=int(input('''
What do you want to know:

  1. Download speed
  2. Upload speed
  3. Both Download and Upload
  4. Ping
    Your choice: '''))

if option<1 or option>4:
sleep(2)
print('You have entered wrong choice, please enter again with values from 1 to 4')
else:
sleep(1)
print()
print('Pls wait, test in progress...')
print()
down_speed=round(speed.download()/1000000,3)
up_speed=round(speed.upload()/1000000,3)
print('One more sec please...')
sleep(2.5)
print()
if option == 1:
print('Your Download speed is: ',down_speed,'Mbps')
elif option == 2:
print('Your Upload speed is: ',up_speed,'Mbps')
elif option == 3:
print('Your Download speed is: ',down_speed,'Mbps',end=" ")
print(',and your Upload speed is: ',up_speed,'Mbps')

elif option == 4:
    s=[]
    speed.get_servers(s)
    print(speed.results.ping,'ms')
else:
    print('Sorry, something went wrong, pls try again...')
lucid vine
coral flicker
regal pulsar
#

Try speed=speedtest.SpeedTest()

hollow badger
#

Wavelink is a way of streaming music no. I doubt you have a license to stream music to others, so that would be against the ToS of every source of that music. A common source is YouTube, hence the ytdl embed.

lucid vine
coral flicker
#

And we don't help with projects that involve things that break tos, even if the problem isn't in that part.

sick birch
hollow badger
#

I never said you were. I am saying wavelink is the issue.

lucid vine
#

what if im using a opensource api that uses uncopyrighted music

heady sluice
regal pulsar
#

hmm

slate swan
lucid vine
#

making up stuff cuz u have a quarell with me

heady sluice
#

can a mod just end this

lucid vine
#

"quarell"

regal pulsar
#

well

slate swan
regal pulsar
#

ok

sick birch