#discord-bots

1 messages · Page 1156 of 1

wild spoke
#

ig. it can send messages

livid hedge
#

i posted the code

slate swan
livid hedge
#

.

slate swan
#

Enable intents.message_content

slate swan
wild spoke
slate swan
#

If you don't read, that's your fault

slate swan
unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

livid hedge
#

still doesnt work

slate swan
#

Did you even reinvited your bot with the correct scope

winter gull
#

I have just noticed that if i ran a command and instantly run the same or any command again. It takes time to run the second command till the first one is completed. I dont want this to happen

livid hedge
faint sapphire
#

idk if it possible to do these with requests.post()

livid hedge
#

but I also readded

slate swan
#

In that vase share more of the code, only those lines are not the root cause of your issue

wild spoke
faint sapphire
wild spoke
#

Im clearly doing something wrong here

slate swan
livid hedge
#

await bot.tree.sync(guild=discord.Object(id=int(GUILD)))

wild spoke
slate swan
slate swan
wild spoke
#

maybe I should put it under a class?

slate swan
#

Like intents=intents

livid hedge
#
prefix = '!'
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix=prefix, intents=intents)
bot.synced = False
bot.remove_command("help")

@bot.event
async def on_ready():
    await bot.wait_until_ready()
    if not bot.synced:
        await bot.tree.sync(guild=discord.Object(id=int(GUILD)))
        bot.synced = True```
slate swan
#

Bascially this part

#

did you invite the bot with application commands scope

wild spoke
#

just copypaste?

slate swan
#

You define bot only once, never twice

wild spoke
slate swan
#

set it as an attribute of the class, and use self.<the variable assigned> to access it

livid hedge
wild spoke
#

english is hard man

#

like that?

slate swan
#

That's not how cogs work

wild spoke
livid hedge
#
wild spoke
#
asyncio.run() cannot be called from a running event loop```
#

tho bot is still running

slate swan
robust fulcrum
#

Guys anyone here have hikari tutorial?

faint sapphire
#

im tryna see if its possible to automate interactions with applications through slash commands

idk if its possible to do requests.get to get the variables to fill the payload then make the requests.post

payload needs: session id and data

slate swan
robust fulcrum
#

Oh thanks

sleek palm
#

Hey how can i do so my bot would say "You are the 160th member"?

I want the bot to display st, rd, th behind the number

faint sapphire
#

your welcome

sleek palm
slate swan
unkempt canyonBOT
#

property member_count```
Returns the member count if available.

Warning

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

Changed in version 2.0: Now returns an `Optional[int]`.
sleek palm
tacit horizon
#

can I prevent bot crashing if the network gone

slate swan
#

I made a discord bot which shares reddit submissions randomly as an embed whenever the command is sent, can i make it such that it shares only images?

slate swan
slate swan
tacit horizon
slate swan
sick birch
#

Home networks aren’t as good as getting back up

faint sapphire
#

is it possible to automate interactions with apps through slash commands

it seems all thats needed is to get session id and some variables to fill the payload for the requests.post

#

im just not sure about the syntax to try all these things

sick birch
#

Yes, though I believe that’s against terms of service

faint sapphire
#

keep = message.content.split(",",1)[0]

slate swan
sick birch
#

Personally, I have a pretty reliable network so I used to host it on my RPI 4 before switching to AWS EC2. We still had network & power outages but we’re resolved swiftly

faint sapphire
#

why not use heroku?

#

AWS EC2 is free it seems anyway

sick birch
#

We don’t recommend heroku

slate swan
#

As I work in AWS myself, I am actually tempted to switch over cause I know I could keep usage down and not rack up a bill in the 1000s lol. But DigitalOcean have always been just as good for smaller projects really, I am looking at some PIs myself soon for a cluster service.

#

AWS EC2 is not free lol.

sick birch
#

But honestly feels too low end

sick birch
slate swan
#

Do NOT use AWS if you have no skillset with it, its an enterprise solution and I see it happen daily with people running bills into 1000s because they don't know what they are doing. I mean I just work with AWS tech, sorry my wording can be awful at times.

I would always recommend digital ocean as its very user/new person friendly, and very easy to just fire up a Linux VM with little effort.

faint sapphire
#

how are bots able to respond to multiple users at the same time
i see mine can only handle the same command one at a time

sick birch
#

Doesn’t AWS have methods to limit billing expenses?

sick birch
faint sapphire
#

i dont use bot commands

#

i guess its obvious then

#

but im not sure replacing with botcommands makes a diff

sick birch
#

Okay.. Can we see the code for the on message?

faint sapphire
#

ok

sick birch
#

No indeed. As Jammy mentioned, it’s an enterprise solution

faint sapphire
#

that type of stuff

sick birch
#

Is that everything?

#

Seems like some stuff is cut off

vale wing
#

Seeing all those splits makes me think you are implementing arguments this way

sick birch
#

Using commands would remove all the manual parsing

haughty nova
#

Hello! I want to do a command that write an embed message like this https://gyazo.com/43af9a54d39500694f4ea46094e5dc37

When I write the command !sregler it just sends like this https://gyazo.com/936d31e20543a6ebc67a26efb070a6ab

the code:
https://www.toptal.com/developers/hastebin/babumelegi.py

sick birch
haughty nova
winter gull
#

I asked this question earlier and did not got any response, i really need help with this.
The bot which i am working on does not respond to any other or same command unless and until the previous command is fully executed. I don't know why this is happening

sick birch
sick birch
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.

winter gull
#

I can stream you the delay that is happening if you wish to

sick birch
#

For the 2nd command, I'm guessing this part is blocking:

JavaServer.lookup('play.timepvp.in').status().players.online

you'll have to find a non-blocking alternative to this

#

As for the first command, I'm guessing it's all of the kitpvp...() methods

#

For which, again, you'll have to find a non-blocking alternative

winter gull
#

hmm

#

I just dont understand about other commands like

#

for example,
The stats command i have enabled a guild cooldown of 5 seconds, even that is considered a command ran by the user when the previous command has fully executed

#

I know about creating a task in asynchronous programming. but dont know how to implement it here

sick birch
#

You could try create_task, might be worth it

#

But the better option would be to find a non-blocking, asynchronous alternative to the JavaServer and kitpvp modules

winter gull
#

the kitpvp module was created by me

#

it's a class which fetch data from a MySQL database

#

I can show you the class if you want to look into that?

sick birch
#

Ah okay. How are you interfacing with a MySQL database?

#

I'm guessing that's where the problem lies

winter gull
#

mysql connector - python

sick birch
#

Can you send me the pypi page?

winter gull
#

yes

sick birch
#

Well there's your issue

#

It's not asynchronous and blocking

#

You'll need to switch to an asynchronous mysql connnector

winter gull
#

would it make a difference that when the bot starts, the mysql connection is made due to i create an instance of the class before hand (dont worry i close the database after the bot is stopped and the data is committed after 60 seconds)

sick birch
#

No, you need to switch over libraries

#

Personally I can't recommend any good ones as I've never used mysql, but you might have luck asking in #databases for python async aiosqlite connectors

winter gull
#

so like making the fetching of data asynchronous?

winter gull
#

how do I send a message as a response to the user who ran the command?

sick birch
#

Just ctx.send()?

#

Or are we talking about app commands

winter gull
#

no like

winter gull
sick birch
#

!d discord.ext.commands.Context.reply

unkempt canyonBOT
#

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

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

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

New in version 1.6.

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

ty

outer fog
#

it tells you the Attribute error

sick birch
slate swan
#

you really shouldnt use the internal session the bot class has

#

im pretty sure it passes your Bot token into a header for each request

slate swan
#

need to use .http._HTTPClient__session for that iirc

slate swan
#

pikachu_whoa this is cool

pliant gulch
#

Discord PR staff: How the hell do we get people to get excited about the old discord API
Also discord PR: Just add a badge people will do anything for them

slate swan
#

noone's gonna complain about slash commands now, cause badges are ✨ cool ✨

hybrid fjord
#

how do i store data within my bot?

slate swan
shrewd apex
#

...

slate swan
hybrid fjord
#

permanent

shrewd apex
shrewd apex
hybrid fjord
#

i did a bit of googling and i'm to put the filename in .gitignore which is what i'm trying now

#

levels, warnings and so on

shrewd apex
#

make a SQL db

hybrid fjord
#

i'll try that second

shrewd apex
#

whats first then?👀

#

SQL db seems simplest to me

shrewd apex
#

another thing u can use is mongodb

shrewd apex
#

;-;

slate swan
#

yet I have installed it, how can I fix it?

#

I thought Discord added a new badge for badge hunters, but no it's for the bot KEKW

shrewd apex
#

huh? .gitignore dosent store stuff

hybrid fjord
#

yes but i can stop it from resetting everytime i run the bot

shrewd apex
hybrid fjord
#

which is what it does currently

slate swan
slate swan
shrewd apex
shrewd apex
#

or if u don't wanna learn SQL us a nosql db like mongo

hybrid fjord
#

👍

slate swan
#

and not JSON

slate swan
slate swan
shrewd apex
slate swan
#

okay thanks

shrewd apex
#

?

slate swan
#

imagine mongo sheesh

shrewd apex
#

what's wrong with it

paper sluice
slate swan
#

hmm point

#

but i gotta work soo

shrewd apex
#

it's 7 something in uk og

slate swan
#

8

shrewd apex
#

some how or the other

slate swan
#

ofcourse

#

how do i delete server template and create a new one

#

and send the url of the new one

rough kraken
#

I want to develop a bot that automatically bumps my server after the discord bumper time is over. I am very new to bot development , so the only solution currently i can think of is that i run the /bump command once and then let the bot reply to that msg with /bump in the specific time interval. So he keep on going... I dont know if its the efficient way. Could someone please guide me abit on that? Is there a specific function in the discord api?

@bot.event
async def on_message(msg):
    username = msg.author.display_name
    #if msg.author == bot.user:
        #return
    if msg.content == '/bump':
        await msg.channel.send("/bump " + username)
slate swan
#

use @tasks.loop()

#

I don't think slash commands just works by sending the command prefixed with slash...?

#

true

slate swan
slate swan
#

No

rough kraken
#

is there another way to run a command then

slate swan
#

They works on completely different endpoints

#

You can send http requests to this route but I wonder if discord allows bots to run slash commands

#

Also most bot developers themselves ignore bots, even in gateway commands. So I don't think there's any way to do that

rough kraken
#

:/

#

ok thank you

slate swan
unkempt canyonBOT
#

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

Gets the list of templates from this guild.

Requires [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permissions.

New in version 1.7.
slate swan
sick birch
rough kraken
slate swan
#

[<Template code='gQ5USdenfeRFbUDW' uses=0 name='🂱🂶 Backup_AW' creator=<User id=999636884923883531 name='Meft' discriminator='6dedef10' bot=True> source_guild=<Gefefeild id=921366728016011324 name='eedefd🂶' shard_id=Nonefe chunked=False meefmber_count=469690>>]

#

@slate swan

sick birch
slate swan
#

help me

slate swan
slate swan
#

how do i choosee it

rough kraken
outer flint
#

has anyone replicated the Dyno's action log? thinko

slate swan
sick birch
slate swan
#

There used to be a way... which was against tos..

slate swan
#

There are still more ways but yeah they all break tos one way or other

#

i want it to print https:template.f//isKJnifnI6

slate swan
#

For code, you need to template.code

#

!d discord.Template.code

unkempt canyonBOT
slate swan
#

niceeeeeeeeeeeeeeee

#

And to get url, prefix https://discord.new/ before the code

#

okay

sick birch
#

That’s out of my expertise, sorry

faint sapphire
#

i couldnt find these 3 things ig the Get response

patent lark
#

i’m sorry, what?

slate swan
#

what are you even trying to do

faint sapphire
#

so im trying to figure out where the info used in this

#

is found in that

patent lark
#

i think you’re in the wrong channel bud.

faint sapphire
#

oh yh i think networking i should go to

#

mb

slate swan
#

why are you trying to read the raw responses and requests tho

cerulean folio
#

ok so after recommendations about rate limits it's coming from replit, I hosted my bot on google cloud virtual machine and got this error

slate swan
#

you are probably doing something which is making a lot of reqs

#

!paste mind showing your complete code

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
#

!d discord.Member.avatar

unkempt canyonBOT
#

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

avatar_url has been removed

sick birch
#

!d discord.Member.avatar.url

slate swan
#

!d discord.Asset.url

unkempt canyonBOT
slate swan
#

Avatars are now an Asset too

cerulean folio
# slate swan !paste mind showing your complete code

i can show you my complete project sarth but i won't show it here because the code is very very long and might contain sensitive parts i don't want to share. shall i dm you and add you to the github repo so u can see it?

slate swan
#

user.avatar.url to be more specific

cerulean folio
#

it's been some time i'm thinking to show the whole project to someone experienced that could give me some tips to clean/improve the structure so yeah

slate swan
#

That's some issue with your image processing. #media-processing would be a better place for this

#

I don't know anything about PIL

#

Also you can just use Asset.read() function instead of making separate requests to download the image

modern fiber
#

Is this really possible?

cold sonnet
#

yes

slate swan
#

Uhh my keycap just broke 💀 rip

slate swan
#

If I made a bot with 5 features, would you recommend me to use cogs (5 files) or just smash them all into one ugly file?

#

depends on what the commands are, i categorise commands usually

#

but still, 5 beautiful files, or one ugly smashed file?

slate swan
#

But still cogs are recommendable over just one file, with lets say 40 commands.

#

That's completely subjective. Some people like to smash all 1000 lines in single file and others like to make a cog for every command. Do whatever you like. Though I'd recommend more than ~10-20 commands should be into cogs

#

for 40 commands yes, but i wont do a extension file for just 5 commands if they aint too long

#

also, cog != extension, you can create cogs in your main file itself in case categorising commands is your only need

jovial dock
#

can i make my bot automatically send a message and @ someone each hour?

slate swan
#

!d discord.ext.tasks.loop yes

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
jovial dock
slate swan
#

you can use this decorator on a coroutine, the coroutine will get triggered after each mentioned time

modern fiber
#

!editor

#

.

hidden snow
#

hey i cant get slash commands to work, it says import "discord_slash' could not be resolved,
how can i fix this, for reference i did pip install discord-slash commands or whatever the pip was

from discord_slash import SlashCommand, SlashContext
from discord.ext import commands

client = commands.Bot(command_prefix='!')

@client.command(
async def ping(ctx):
await ctx.send('Pong!')

slate swan
#

stop using 3rd party libraries, just use discord.py master or a fork instead

hidden snow
#

what are those?

#

if i move all my code into it would i need to import any discord related modules

slate swan
#

its not an app or something

#

its a python library

hidden snow
#

so what about my imports are 3rd party?

slate swan
slate swan
hidden snow
#

oh

#

and the solution is to follow that tutorial

quaint epoch
#

!D discord.ext.tasks.Loop

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
hidden snow
#

@slate swan it still doesnt work

slate swan
hidden snow
#

i did not read the gist to be honest

#

you know, thats my bad, i hate reading, ill hit the books and actual understand what u sent

cold tide
#

Can anyone help me with setting up errors for using commands in the wrong channels?

hardy wing
#

trying to host my bot on heroku and it's saying "App not compatible with buildpack" with my buildpack being python and the bot being coded with it, any idea how to fix this?

hybrid fjord
#
@tree.command(name="hierarchy",description="Get a list of staff members.",guild = discord.Object(id=guildID))
async def self(ctx: discord.Interaction):
  channel = ctx.guild.get_channel(998715594809548850)

  roles = {
    "Owners":998412738109898812,
    "Co-Owners":998413729370755093,
    "Admins":998414999590547456,
    "Moderators":998414468570681405,
    "Developers":998415323621503078
  }


  embed = embed=discord.Embed(title="Staff Members", description="", color=0x2f3137)
  for i,v in roles.keys():
    members = []
    for i2 in (discord.utils.get(ctx.guild.roles, id=v)).members:
      members.append(i2.mention)
      listOfMembers = members.join("\n")
    embed.add_field(name=f"{i}",value=f"{listOfMembers}",inline=True)

  await ctx.response.send_message(embed=embed, ephemeral=True)```
Any ideas?
#

no line number

sick birch
#

roles.keys() will return just the keys of your dict as a list

hybrid fjord
#

Ah, I see

#

So just roles, no .keys()?

sick birch
#

!e

my_dict = {
  "hello": "world",
  "some key": "some value",
}

print(my_dict.keys())
unkempt canyonBOT
#

@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.

dict_keys(['hello', 'some key'])
hybrid fjord
#

makes much more sense. thank you

sick birch
#

If you want both key & value, try .items()

hybrid fjord
#

got it 👍

sick birch
#

!e

my_dict = {
  "hello": "world",
  "some key": "some value",
}

for k, v in my_dict.items():
  print(f"Key: {k} | Value: {v}")
unkempt canyonBOT
#

@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Key: hello | Value: world
002 | Key: some key | Value: some value
hybrid fjord
#

thats actually what i was going for, but recently came back to python so must've got them muddled up

sick birch
#

Common issue, no worries

#

Also from what you said about "no line errors", I think you should get that fixed. I'm guessing the issue is that in your error handler, you're just doing something like print(e), but a better method would be to either re-raise it (raise e), or use the traceback library to print_exc()

hybrid fjord
#

Ah. Thank you for the tip

#

any way to have a set option for d.py 2.0 slash commands? for example, one parameter has either "yes" or "no"?

jovial dock
#

would this work? last time i used the top bit of code was a bit ago and i used a different way of coding my bot

hybrid fjord
#

in between the async def and list

jovial dock
#

thanks

torn sail
#

Literal["yes", "no"]

hybrid fjord
#

care to link me a doc or something? been searching for ages

torn sail
#

I’ll see if I can find it

hybrid fjord
torn sail
#

As a typehint for the parameter

hybrid fjord
#

async def self(ctx: discord.Interaction, Literal["yes", "no"]):?

torn sail
#

async def self(ctx, option: Literal["yes", "no"])

hybrid fjord
#

ah, let me try

#

glowing yellow. any fix?

torn sail
#

not sure what it means

hybrid fjord
#

not defined

torn sail
#

from typing import Literal

hybrid fjord
#

ah

jovial dock
#

is discorx.ext differend from discord, i forgor

cold tide
#

Can anyone help me with setting up errors for using commands in the wrong channels?

jovial dock
torn sail
cold tide
#

@torn sail Can you help me?

torn sail
jovial dock
jovial dock
#

thanks

cold tide
#

Legit just need source loll

torn sail
# cold tide Nope.

how do you want the check to be applied? all commands, some commands, etc

cold tide
#

im not too good with handling errors lol

hybrid fjord
#

@torn sail slash options worked. Much appreciated 🙌

torn sail
#

!d discord.ext.commands.check

unkempt canyonBOT
#

@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").

These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
cold tide
#

@torn sail So how would i use this?

torn sail
#

I would make the predicate raise a custom error and handle it in an error handler

sick birch
terse coyote
#

i'm handling err commands.errors.MemberNotFound, and do this with on_command_error. I have 2 this handlers. And when im have this error, my 2 handlers working. How to handling errors like a normal people?

torn sail
#

like this

class WrongChannel(commands.CheckFailure):
    pass


def check_channel(ctx):
    if ctx.channel.id not in [2329834234, 234723423]: # some channel ids here
        raise WrongChannel()

    return True


@commands.command()
@commands.check(check_channel)
async def command(ctx):
    ...
sick birch
hybrid fjord
#

crazy.. has it changed from 1.0 to 2.0?

sick birch
torn sail
hybrid fjord
#

bruh wow

sick birch
#

It's plural, you can add multiple roles at once which is why

hybrid fjord
#

yeah makes sense

terse coyote
#

ok, i wanna to handle commands.errors.MemberNotFound repeatedly. How can i do this?

jovial dock
sick birch
sick birch
torn sail
#

only works for text channels

#

i think

cold tide
#

@torn sail ```class WrongChannel(commands.CheckFailure):
pass

def check_channel(ctx):
if ctx.channel.id not in [998928038047780935]:
raise WrongChannel()

return True

@commands.command()
@commands.check(check_channel)
async def command(ctx):
channel=discord.Embed()
channel=discord.Embed(title="🤖 ERROR 🚫",description=f"Command used in the wrong channel {ctx.author} !",color=0xffff00)
await ctx.reply(embed=channel)``` when running cmd in wrong channel no error is raised

jovial dock
#

originally the code was just this, but i want to make it only work in my nsfw channel

sick birch
# jovial dock yep

So something like

def is_nsfw():
  async def predicate(ctx: commands.Context):
    return ctx.channel.is_nsfw()
  return commands.check(predicate)

@bot.command()
@is_nsfw()
async def nsfw_only_command(...):
  ...

@bot.command()
@is_nsfw()
async def another_command(...):
  ...
#

You can reuse it in as many commands as you want

cold tide
#

easy lol

#

It will only excute if cmd is run in the right channel

torn sail
cold tide
torn sail
#

hmm do you have a error handler

sick birch
#

!d discord.TextChannel.nsfw

unkempt canyonBOT
jovial dock
#

thanks for the help

sick birch
#

ok i guess it does exist

cold tide
torn sail
#

did u add the command to the bot?

cold tide
#

yes.

torn sail
#

ok just making sure lol

cold tide
#

When i tried in the wrong channel no error was raised.

torn sail
#

oh wait

cold tide
#

The command just didnt work loll

torn sail
#

wait so how do you want it to work

cold tide
#

So if a user executes are certain command in the wrong channel it responds with for example f"ERROR {ctx.author} Command used in wrong channel !"

torn sail
#

and then you need to make a error handler

cold tide
#

Mind showing me??

torn sail
#

sure

cold tide
#

i have 0 experience with error handling lol

#

I have alot of learning to do

jovial dock
#
async def on_message_edit(before, after):
    await before.channel.send(
        f'{before.author} edit a message.\n'
        f'before: {before.content}\n'
        f'after: {after.content}'
    )```
is there a way to fix this? as shown before i have the large dumb and cant do basic troubleshooting because i watch too many tutorials
torn sail
# cold tide Mind showing me??
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, WrongChannel):
        await ctx.send('Wrong channel')
    else:
        raise error
cold tide
#

Okay ty! And one last question !

sick birch
torn sail
#

yes

cold tide
#

How would you set up 2 diff commands that raise a error if your missing roles? Without it getting confused

torn sail
#

im not sure waht you mean

#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
sick birch
# unkempt canyon

This check raises one of two special exceptions, MissingRole if the user is missing a role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

#

You can catch those errors

cold tide
torn sail
cold tide
#

@bot.event async def on_command_error(ctx, error): if isinstance(error, WrongChannel): await ctx.send('Wrong channel') else: raise error

#

No error is raised when i run the cmd in the wrong channel.

torn sail
#

show how you use the check on the commands

cold tide
#

Heres for missing roles

#

@bot.event async def on_command_error(ctx, error): error=discord.Embed() error=discord.Embed(title=f" 🤖 ERROR 🚫 ",description=f"{ctx.author} premium role is needed to run this command !",color=0xffff00) await ctx.reply(embed=error)

#

I need a smiliar one for wrong channel if you understand.

torn sail
#

you should make sure the error is the correct error

#

if isinstance(error, commands.MissingRole):

cold tide
#

it works perfectly fine though

torn sail
#

and then you can use elif isinstance(error, WrongCHannel):

cold tide
torn sail
sick birch
torn sail
#

otherwise every non related error will also send that

cold tide
#

So thats why when i misspell the cmd it still sends that

torn sail
#

yep

cold tide
#

Ohh okay

#

hold on lemme add that and try it

torn sail
#

make sure to add

else:
    raise error
cold tide
#

Invalid syntax

torn sail
cold tide
#

Indented?

#

Or not

torn sail
#
if <something>:
    ...
elif <something>:
    ...
else:
    ...
#

like this

cold tide
#

Still throws a error

torn sail
#

show code

cold tide
#

@bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRole): else: raise error error=discord.Embed() error=discord.Embed(title=f" 🤖 ERROR 🚫 ",description=f"{ctx.author} premium role is needed to run this command !",color=0xffff00) await ctx.reply(embed=error)

torn sail
#

the else should be after the stuff in the if statement

cold tide
#

its gonna be sumthing stupid ik

#

😭

torn sail
#
if isinstance(error, commands.MissingRole):
    # do stuff
    ...
else:
   raise error
cold tide
#

Oh okay

sick birch
#

By the way, raise ... acts as sort of a return so nothing after it would run

torn sail
#

yeah

jovial dock
#
async def on_message_edit(before, after):
    await before.channel.send(
        f'{before.author} edit a message.\n'
        f'before: {before.content}\n'
        f'after: {after.content}'
    )```
when someone or my bot sends a link with an image and it doesn't instantly load, it will send a message thinking it was edited, can i fix it or will it just have to be like this
cold tide
#

Bruhhh

#

@torn sail nope

#

Do you mind sending me just the complete code???

sick birch
sick birch
torn sail
cold tide
#

i really cant be bothered to sit here and wait dont have much time tbh

jovial dock
sick birch
cold tide
sick birch
#
if not (before.attachments and after.attachments):
  ...
jovial dock
cold tide
sick birch
jovial dock
#

!docs

unkempt canyonBOT
jovial dock
#

there is!

#

different docs though

torn sail
# cold tide That would help 100% !
class WrongChannel(commands.CheckFailure):  # making our own custom error
    pass 

def check_channel(ctx):
    if ctx.channel.id not in [834823423423423, 2323423423423]: #channel ids
        raise WrongChannel()
    return True

@bot.command()
@commands.check(check_channel)
async def random_command(ctx):
    ...

@bot.event
async def on_command_error(ctx, error):
    # our error handler
    if isinstance(error, WrongChannel): # checking if this is the error we want
        await ctx.send('That was the wrong channel')
    else:
        raise error # re raise the error so we don't eat up every error
#

make sure that you understand what is happening in this

cold tide
#

Ill make sure i have a read up online on this

#

But im only in a rush thats all lol and thankyou

torn sail
#

the docs might also have helpful stuff too

cold tide
#

so what does the randomchannel do?

jovial dock
#

where do i import this? i keep seeing that it wants to come from email instead of discord, or does message not exist

cold tide
torn sail
#

i dont see a randomchannel

#

random_command?

cold tide
torn sail
#

im not sure i see that but if you mean random_command thats just an example function for the example command

terse coyote
#
if self.client.top_role < member.top_role:
            embed = discord.Embed(description = f'{author.mention}**stop**')
            await ctx.send(embed = embed)

with this⬆️ command dont working. How to check this

sick birch
jovial dock
#

@bot.event

#
async def on_message_edit(before, after):
    if not message.attachments:
     await before.channel.send(
         f'{before.author} edit a message.\n'
         f'before: {before.content}\n'
         f'after: {after.content}'
    )```
#

this is happening

#

if it doesn't load in immediately then it will detect it as a change so it sends that message

sick birch
#

you'll want to check both before and after

jovial dock
sick birch
jovial dock
#

thanks

#

idk how i've gone this far into my bot without realizing that

slate swan
#
  File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 456, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Clicks\Desktop\Timmy (smile)\bot.py", line 383, in on_message
    @commands.has_permissions(manage_messages=True)
AttributeError: 'str' object has no attribute 'contains'```
#

what??????

#
@client.command(aliases=['clear', 'prune'])
@commands.cooldown(1,10,commands.BucketType.user)
@commands.has_permissions(manage_messages=True)
async def purge(ctx, amount=11):
    amount = amount + 1
    if amount > 101:
        await ctx.send('Can not delete more than 100 messages at once!')
    else:
        await ctx.channel.purge(limit=amount)
        await ctx.send('Cleared the messages requested by {}'.format(ctx.author.mention))
        await ctx.message.delete()```
sick birch
#

Looks like parts of it are chopped out

slate swan
#

that is the full error

sick birch
#

Hmmm.. errors are usually much longer. Are you sure?

#

Because what the error is saying and the code you sent don't seem to match up

slate swan
#

I re-launched vs code and it seems to fix the problem

slate swan
sick birch
#

Strange. Maybe VSCode is just being strange

#

At least the restart fixed it. Hopefully it doesn't happen again

slate swan
#
@client.command()
@commands.is_owner()
async def blacklist(ctx, member: discord.User):

    embed = discord.Embed(title = "User Blacklisted", description = f"A user was added to the blacklist", Timestamp = ctx.message.created_at)
    embed.add_field(name = "Member Blacklisted:", value = f"{member.name} : {member.id}")

    client.blacklisted_users.apped(member.id)
    data = read_json("blacklist")
    data["blacklistedUsers"].append(member.id)
    write_json(data, "blacklist")
    await ctx.send(f"**{member.name}** | **{member.id}** has been **__BLACKLISTED__** from using Timmy")```
#

no response

#

oh wait, im dumb

#

nvm

#

nvm the nvm

#

it doesnt work, no errors, no nothing

jovial dock
#
async def called_once_a_day():
    message_channel = bot.get_channel(999841816809582642)
    print(f"Got channel {message_channel}")
    await message_channel.send("")```
is there a way to also get my friend's Discord profile picture every 15 minutes and send it along with the message?
#

every 15 minutes it @crimson bridge my friend and i want it to also send his pfp

#

sorry whoever i @ ed

sick birch
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
sick birch
#

make sure you actually use the instance, not the class

eternal fox
jovial dock
jovial dock
slate swan
#

it's also called every 15 mins, idk if that's intentional?

jovial dock
#

how do i add aliases?

#

to commands

paper sluice
jovial dock
#

i like your funny words magic man

paper sluice
#

its just

#
@...command(..., aliases=[...])
polar granite
polar granite
#

Its replit

#

Yes

#

Yes

#

Wait giving you replit multiplier link

#

How to do that?

#

@languid wagon see dm

#

I share replit link

eternal fox
slate swan
#

why is that?

#

not true, IDs are related to the time which the snowflake was created, so it can be random

slate swan
vocal snow
#

do global slash commands still take an hour to register?

slate swan
vocal snow
#

okie ty !

slate swan
#

👍

slate swan
#

yeah

#

why are new ids getting a new digit? running out of possibilities?

#

and what makes the ids longer?😅 😭

#

im not sure what youre referring to😅

#

ah cuz unix timestamps start from jan 1970 and its all in seconds or?

#

im not very familiar with unix's timestamp system

hasty loom
#

can anyone send any gh repos which use the official discord.py library for implementing slash commands?

slate swan
#

yep

slate swan
#

true, but most of the forks suck 🚶‍♂️ including pycord

hasty loom
slate swan
hasty loom
#

ohh yeah i forgot abt that

slate swan
#

for an extension file you would be bot.add_cog inside a setup function, whereas in the main file you can do add_cog directly

hasty loom
#

from what i understand in the docs, you have to use @app_commands.describe() to set the params for the slash commands, but how do i specify the data type of them?

placid skiff
#

the error is explainfull, the aiohttp session must be initialized inside an async function

hasty loom
hasty loom
#

and how do i specify whether its required or not

unkempt canyonBOT
#

examples/app_commands/basic.py lines 70 to 75

@client.tree.command()
@app_commands.describe(member='The member you want to get the joined date from; defaults to the user who uses the command')
async def joined(interaction: discord.Interaction, member: Optional[discord.Member] = None):
    """Says when a member joined."""
    # If no member is explicitly provided then we use the command user here
    member = member or interaction.user```
slate swan
robust fulcrum
#

Hi all

dusky pine
slate swan
slate swan
#

sheesh did I forget to update the gist brb

robust fulcrum
#
@commands.Cog.listener("on_message")
    async def message(self,message):
        api  = os.environ['key']
        message = message.content
        analys = perspective(message,api)
        toxicity = analys.toxicity()
        await message.channel.send(f"toxicity of your message is **{toxicity}**")

How to fix this error?

slate swan
robust fulcrum
#

Oh

robust fulcrum
slate swan
#

yes

#

change it to smth like message_content

robust fulcrum
#

Oh ty

robust fulcrum
slate swan
paper sluice
paper sluice
#

or atleast dpy's implementation

hasty loom
#

i know that but like for the main function

#

for asyncio.run(main()) i cant await that cus its not in an async function

#

yeah

dusky pine
cerulean folio
#

Guys I'm getting a bit error log that starts with

2022-07-22 09:46:28 WARNING  discord.http We are being rate limited. POST https://discord.com/api/v10/channels/855852976630923274/messages/999975711190306836/crosspost responded with 429. Retrying in 1167.26 seconds.

anyone knows where this come from?

cold sonnet
#

too many API calls/requests

#

or just replit

misty nexus
#

I do have Intents included like this:

intents = disnake.Intents(messages=True, members=True)
bot = commands.Bot(
    command_prefix=".",
    intents=intents
)
bot.add_cog(Main(bot))
``` But guild.members is completely empty, I can't even get the thumbnail (guild icon) or any data at all. ?
cerulean folio
cold sonnet
#

where are you getting data

cold sonnet
slate swan
misty nexus
misty nexus
# cold sonnet where are you getting data
    @commands.command(help="Get information about server", aliases=["serverinfo"])
    async def server(self, ctx: commands.Context) -> None:
        """Shows you information about this server."""

        guild = ctx.guild

        offline_members = 0
        online_members = 0
        print(guild.members)
        for member in guild.members:
            member: disnake.member.Member

            if member.status != disnake.member.Status.offline:
                online_members += 1
            else:
                offline_members += 1

        embed = Embed(
            title=guild.name,
            colour=COLOR,
        )
        embed.set_thumbnail(guild.icon if guild.icon else 'https://cdn.discordapp.com/embed/avatars/1.png')
        embed.add_field(name="Total Members", value=guild.member_count, inline=False)
        embed.add_field(
            name="Members Status",
            value=f"⚪ Offline: {offline_members}\n🟢 Online: {online_members}",
            inline=False,
        )
        await ctx.send(embed=embed)
slate swan
#

how else do you think you would be able to acess a server's icon

#
intents = disnake.Intents.default()
intents.members = True
``` something like this would work
misty nexus
slate swan
merry cliff
#

remember to check the members intent on the dev portal too

cold sonnet
#

that would raise an error

misty nexus
cold sonnet
#

any task? anything in on_ready?

robust fulcrum
dusky pine
#

which is kind of annoying

cerulean folio
#

the code that did this is bot.run(token)

#

i have no clue about where this come from

robust fulcrum
misty nexus
#

How do I make the time I get from user.joined_at or user.created_at a time stamp?

#

they looks like:

slate swan
#

!d discord.utils.format_dt

unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
misty nexus
gilded gust
#

Hey, I've got a bot in py-cord. I have an interaction and want to respond to it twice, but I get an error ```
discord.errors.InteractionResponded: This interaction has already been responded to before