#discord-bots

1 messages · Page 737 of 1

torn sail
#

Yep

heavy folio
#

oh i got it wrong mv

#

mb

slate swan
#

do any of yall know how to stop an asyncio command from running?

slate swan
#

returns a function and stops the function

slate swan
#

return?

#

it returns the function which stops it

#

like I wish to make a timer function to my discord bot

#

but i want a cancel command

#

where it stops the timer

#

well you can make a var and check the var value and stop the command ig

#

I see thanks

#

yw

tender estuary
#

My bot has the same pfp as you do wow

slate swan
#

overused

torn sail
tender estuary
#

Any idea how I can make heroku update my .json file...

#

It simply isn't updating it... When I run the bot locally it does, but when I host in on heroku it does not write in the .json file.

slate swan
#

heroku does not allow you to change any files , it reverts back to its original condition

tender estuary
#

Oh ok

#

Is there any way I can make this possible?

#

I'll probably try PostgreSQL

#

I need a database for economy

slate swan
#

!pypi motor

unkempt canyonBOT
tender estuary
#

thanks..

pliant gulch
#

You'd have to get a database hosted not on heroku

#

Unless heroku has an addon that supports postgres

slate swan
#

a postgres db server maybe?

pliant gulch
#

So as long as it isn't hosted on heroku

tender estuary
pliant gulch
#

Then you'd have to use that

grim oar
#

Just pay for him andy

pliant gulch
#

A regular postgres server on heroku would just reset the data after a restart

grim oar
#

You are quite rich

tender estuary
#

I'll surely look into mongodb tho.. I'd like to keep it similar to json

slate swan
slate swan
exotic patrol
#

I am facing difficulty in updating roles of members when they start/end an activity...

#
@bot.event
async def on_member_update(before, after):
  if str(after.activity) == "GAME1":
    if str(before.activity) != "GAME1":
      v = discord.utils.get_role(abc)
      after.add_role(v)
    else:
      pass
  else:
    try:
      if str(after.activity) != "GAME1":
        if str(before.activity) == "GAME1":
          v = discord.utils.get_role(abc)
          after.remove_role(v)
    except:
      pass```
#

what is wrong here?

slate swan
slate swan
unkempt canyonBOT
#

Return Statement

When calling a function, you'll often want it to give you a value back. In order to do that, you must return it. The reason for this is because functions have their own scope. Any values defined within the function body are inaccessible outside of that function.

For more information about scope, see !tags scope

Consider the following function:

def square(n):
    return n*n

If we wanted to store 5 squared in a variable called x, we could do that like so:
x = square(5). x would now equal 25.

Common Mistakes

>>> def square(n):
...     n*n  # calculates then throws away, returns None
...
>>> x = square(5)
>>> print(x)
None
>>> def square(n):
...     print(n*n)  # calculates and prints, then throws away and returns None
...
>>> x = square(5)
25
>>> print(x)
None

Things to note
print() and return do not accomplish the same thing. print() will only print the value, it will not be accessible outside of the function afterwards.
• A function will return None if it ends without reaching an explicit return statement.
• When you want to print a value calculated in a function, instead of printing inside the function, it is often better to return the value and print the function call instead.
Official documentation for return

slate swan
#

can you no longer read message contents of others when using on_message?

slate swan
#

yw

#

I'm coding a game bot using nextcord, and this is the problem I'm facing rn. I have thought of a solution, but I haven't tried it yet.

#

the solution is that I use a global variable

exotic patrol
#
@bot.event
async def on_member_update(before, after):
  if str(after.activity) == "GAME1":
    print("initiated 1")
#    if str(before.activity) != "VALORANT":
    v = discord.utils.get_role(abc)
    after.add_roles(v)
    print("role updated 1")
  else:
    try:
      if str(after.activity) != "GAME1":
        print("initiated 2")
  #      if str(before.activity) == "VALORANT":
        v = discord.utils.get_role(abc)
        after.remove_roles(v)
        print("role updated 2")
    except:
      pass```
shadow wraith
exotic patrol
tender estuary
exotic patrol
tender estuary
#

Ok

exotic patrol
#

like if I start game1 then the bot will give me game1 role and when I stop it, it will remove that role

tender estuary
#

how do you start the game1?

exotic patrol
tender estuary
#

Oh got it

exotic patrol
#

like we play games on among us or valorant and all

#

external game...

tender estuary
#

and what is the problem here?

#

that you are facing?

shadow wraith
#

idk how to fix it tho as i've never used on_member_update

exotic patrol
#

I think I made a mistake around getting the role

tender estuary
#

for getting the role

exotic patrol
tender estuary
#

try using

get_role = discord.utils.get(ctx.guild.roles, name="role name")
shadow wraith
#

wait a fucking second... ive never used on_member_update but do you have a Member object in that event?

exotic patrol
tender estuary
exotic patrol
slate swan
exotic patrol
#

I think it takes 2 arguments only

slate swan
#

on_member_update has no context

tender estuary
shadow wraith
slate swan
#

and only takes 2 positional arguments iirc

exotic patrol
shadow wraith
#

nvm im stupid

slate swan
#

!d discord.on_member_update

unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.

This is called when one or more of the following things change:

• nickname

• roles

• pending...
slate swan
#

see ^

shadow wraith
#

actually don't since it doesn't exist 😭

exotic patrol
shadow wraith
#

that's another way of "fetching" the role

exotic patrol
shadow wraith
#

but i remember i used that before ¯_(ツ)_/¯

slate swan
#

after is a member obj which member doesnt have a guild attr?

tender estuary
#

I am doing commands rn... events just too hard for me atm

slate swan
tender estuary
shadow wraith
slate swan
exotic patrol
slate swan
#

prob

slate swan
#

most events are pretty easy

shadow wraith
#

found it!

slate swan
#

the heck

#

how does that work

shadow wraith
#

istg i think it worked

exotic patrol
shadow wraith
#

alr

exotic patrol
tender estuary
#

Except the on member join and all the ez stuff

#

Well I see events really give life to the bot I'll start events once I am strong with cmds

slate swan
#

ic gl

green bluff
#

ok i did this simple command to troll my friends

#

WHY IS NOT WORKING

slate swan
#

you forgot () in the decorator

green bluff
#

omh

#

im stupudi

#

thanks

slate swan
#

happens

#

yw

green bluff
#

@slate swan can u help m,e with this

#

#giveaway system
@client.command
async def gstart(ctx, mins : int, , reason:str):
embed = discord.Embed(title="Giveaway!", description=f"{reason}", colour=discord.Colour.gold())
end = datetime.datetime.utcow() + datetime.timedelta(seconds = mins
60)
embed.add_field(name="Ends at:", value = f"{end} UTC")
embed.set_footer(text=f"Ends in {mins} miniutes!")
my_msg = await ctx.send(embed=embed)
await my_msg.add_reaction("🎉")
await asyncio.sleep(mins)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
await ctx.send(f'Congratulations {winner.mention} won {reason}!')

#

why does this not work

#
@client.command
async def gstart(ctx, mins : int, *, reason:str):
    embed = discord.Embed(title="**Giveaway!**", description=f"{reason}", colour=discord.Colour.gold())
    end = datetime.datetime.utcow() + datetime.timedelta(seconds = mins*60)
    embed.add_field(name="Ends at:", value = f"{end} UTC")
    embed.set_footer(text=f"Ends in {mins} miniutes!")
    my_msg = await ctx.send(embed=embed)
    await my_msg.add_reaction("🎉")    
    await asyncio.sleep(mins)
    new_msg = await ctx.channel.fetch_message(my_msg.id)
    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(client.user))
    winner = random.choice(users)
    await ctx.send(f'Congratulations {winner.mention} won {reason}!')```
slate swan
#

hey does anybody know why this error is occuring py await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip'

green bluff
#

oh

slate swan
#

This is my code btw ```py
import discord
import os

client = discord.Client()
TOKEN = os.getenv('DISCORD_TOKEN')
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')

client.run(TOKEN)```

green bluff
#

@slate swan

#

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

slate swan
#

yes

green bluff
#

insted of client.run

slate swan
#

but i m storing that in variable

green bluff
#

you have stored ur token in an environment right

#

yes

#

thats why u importedf os

#

in the first place

slate swan
#

im doing that already

green bluff
#

u dont just do client.run

#

oh wait

#

did u do client.run(ahwhdaiwduawd)

#

@slate swan

slate swan
#

nope

green bluff
#

ok im bad at this but the (agwdyawd) is ur token

#

add quotation

#

nvm

slate swan
#

it’s an error in your class or object

green bluff
#

im sorry for wasting ur time

#

lol

slate swan
#

i haven't created my own class yet

#

its the default discord classes

#

object then and it’s returning none

green bluff
#
@client.command
async def gstart(ctx, mins : int, *, reason:str):
    embed = discord.Embed(title="**Giveaway!**", description=f"{reason}", colour=discord.Colour.gold())
    end = datetime.datetime.utcow() + datetime.timedelta(seconds = mins*60)
    embed.add_field(name="Ends at:", value = f"{end} UTC")
    embed.set_footer(text=f"Ends in {mins} miniutes!")
    my_msg = await ctx.send(embed=embed)
    await my_msg.add_reaction("🎉")    
    await asyncio.sleep(mins)
    new_msg = await ctx.channel.fetch_message(my_msg.id)
    users = await new_msg.reactions[0].users().flatten()
    users.pop(users.index(client.user))
    winner = random.choice(users)
    await ctx.send(f'Congratulations {winner.mention} won {reason}!')```
#

flanny can u help

slate swan
#

what’s the error

green bluff
#

no error

#

when i run the command just doesnt respond

#

the bot just doesnt respond to !gstart

#

my prefix is !

slate swan
#

do you have message intents on

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

green bluff
#

yes i have intents on

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

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

this is my code. When I run ;toggleDM enable, then run dm cibere test I still get the dm. And when I do ;toggleDM disable then run dm cibere test, i still get the dm. I get no error in the console, and I have noDM_list = [] earlier up in the code.
pls ping in replies
I am going to bed... so yeah

slate swan
#

Nvm that won't work

#

Do you have an error handler?

maiden fable
#

@frank tartan u r adding and removing user IDs, but in the dm command, checking the member object

honest shoal
#

I made a timeout command py @bot.command() @disnake.ext.commands.has_permissions(manage_nicknames=True) async def timeout(ctx, member: disnake.Member,time: float, *, reason=None) -> None: await member.timeout(duration=time, reason=reason) await ctx.send(f"{member.mention} has been timed out for {time} Seconds, With the reason of {reason}") Currently it only accept duration in seconds how can I have other duration units??

slate swan
#

you can convert other time units to seconds

#

and it accepts datetime object too

#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
honest shoal
honest shoal
#

!d datetime.timedelta

#

No idea how it works

slate swan
#

its basically a difference between two datetime objects

honest shoal
#

any example for it?

maiden fable
#

!pypi humanize

unkempt canyonBOT
maiden fable
#

@honest shoal u can use this too

honest shoal
#

oh, let me see

velvet tinsel
warm mirage
#

i need help

#

im making a fight bot

#

like dank memer

#

but idk how to get the bot to let the player im fighting against like react and fight back

#

i want the game to loop until a player dies

#

but the game does the loop but the discord bot responds and plays the game instead of the opponant player

honest shoal
# maiden fable <@787149777103486986> u can use this too

well a tried a time converter but still it was accepting as seconds sadge, the new code py @bot.command() @disnake.ext.commands.has_permissions(manage_nicknames=True) async def timeout(ctx, member: disnake.Member,time, *, reason=None) -> None: time_convert = {'s' : 1 , 'm' : 60 , 'h' : 3600 , 'd' : 86400} timeout_time = float(time[0]) * time_convert[time[-1]] await member.timeout(duration=timeout_time, reason=reason) await ctx.send(f"{member.mention} has been timed out for {time}, With the reason of {reason}")

maiden fable
#

Uh why u doing time[0] tho

#

@honest shoal

honest shoal
maiden fable
#

And how u invoking the cmd?

honest shoal
#

prefix command

maiden fable
#

The whole invocation

honest shoal
#

Command is working properly it times out the user but in seconds

#

so there's problem with time converter

maiden fable
#

Try printing timeout_time

honest shoal
maiden fable
#

Wait, so on heroku u did 1m as timeout?

honest shoal
#

no 10m

#

and when I tried running directly, it was perfect

slate swan
#

Make sure you've updated the build on Heroku.

honest shoal
#

yes

#

it is

maiden fable
#

Hmm seems more of a code updation problem rather than the logic/code problem

honest shoal
#

printing of timeout_time was another build, so it doesn't seems like updation problem

#

wait

#

I just noticed

#

for all 2 digits numbers it is accepting as 60, works fine for 1 digit numbers on heroku

#

and yeah same when I run directly, accepting 2 digit values as 60

#

@maiden fable

slate swan
#

Well that's normal.

#

Your code only takes the first character and last character of the argument you give when executing the command.

#

So if you use with 76s, it will timeout for 7 seconds.

#

It reads at index 0 (the 7) and at index -1 (the s).

#

Everything in-between is ignored.

honest shoal
slate swan
#

As I said

#

It takes only the first and last character in consideration.

honest shoal
#

oh yea 1m = 60 s

maiden fable
#

Ah, so u can use slicing

slate swan
#

Slice your string from index 0 to len-1

#

!e
x = "653m"
print(x[0:len(x)-1])

unkempt canyonBOT
#

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

653
slate swan
#

Instead of a timeout time of time[0]

daring thicket
#

help me for random number command

honest shoal
#

Thanks @maiden fable @slate swan!

daring thicket
#

please help=(

honest shoal
daring thicket
#

but failed

honest shoal
quick gust
daring thicket
quick gust
#

okay that's easy

#

show your code and the error

daring thicket
quick gust
#

and how did u invoke the command?

#

something like [prefix]random 3?

daring thicket
#

and it is random from 1 to 3

quick gust
#

not sure then

slate swan
#

Type hint your argument to an integer in your command definition.

#
(ctx, range: int)
#

All arguments are read as strings per default and you can't use strings in randint.

green bluff
#

why isntthe join message

#

giving the member a role

daring thicket
green bluff
#
@client.event
async def on_member_join(ctx, member):
    embed = discord.Embed(title="", description="If you are looking for something more, read #tier-rules", colour=0x77DD77)
    embed.set_author(name=f'{member} Welcome to Ace Scrims!', icon_url=member.avatar_url)
    role = discord.utils.get(ctx.guild.roles, name='Member')
    channel = client.get_channel(914825862573064222)
    await channel.send(embed=embed)
    await member.add_roles(role)```
#

code

slate swan
#

on_member_join takes no ctx augment, only a member argument and that's it.

slate swan
green bluff
#

ctx.guild.roles is not working then

slate swan
#

You can access the guild object with member.guild instead of ctx.guild.

#

!d discord.Member.guild

unkempt canyonBOT
green bluff
#

and also

#

can i copy role id and do await member.add_roles(<roleid>)?

slate swan
#

hey anybody here?

green bluff
#

would that work @slate swan

slate swan
#

@green bluff how can i make function that will work only in a specific channel

green bluff
#

ooh i actually havent done that in my code yet

#

so i do not know

slate swan
green bluff
#

u should ask somebody else

#

maybe they can get an answer

slate swan
#

ok np

maiden fable
slate swan
#

Simply replace ctx.guild with member.guild, and remove the ctx parameter.

green bluff
#

yep thanks

unkempt canyonBOT
#

Custom Command Checks in discord.py

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

from discord.ext.commands import check, Context

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

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

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

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

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

slate swan
#

how can find that id in setting?

maiden fable
#

Or this, yea

slate swan
#

Right click the channel and click "Copy ID".

#

ok

#

but id can be different for diff servers

#

Yes.

#

i should come up with a sol

#

IDs are always unique.

harsh stump
#

Where do I start?

cedar stream
slate swan
harsh stump
#

coding discord bots

#

ik python

slate swan
#

Then the quick start is where you should go.

harsh stump
#

okay ty

cedar stream
#

And oop

slate swan
#

Then simply go on by reading the documentation for things you want to do and you're good to go.

harsh stump
cedar stream
#

B4 going into dpy

harsh stump
#

kk

#

btw is there like a place to code or my regular ide?

slate swan
#

Any IDE or text/code editor like VSC is fine.

harsh stump
#

okay

slate swan
#

AttributeError: 'TextChannel' object has no attribute 'delete_message'

#

how can i delete the message by a user

#

message.channel.delete_message isn't working

bitter depot
#

channel.delete_message is like 5 years out of date now

dense coral
slate swan
#

i want to delete a specific message , can i give the arguement?

dense coral
#

await ctx.message.delete()

bitter depot
slate swan
#

like i want to delete the message that triggred this command

bitter depot
slate swan
#

ok

bitter depot
#

You get the discord.Message object and then await the .delete() coroutine

#

The discord.Message that invoked the command is ctx.message

#

So await ctx.message.delete()

slate swan
#

what is ctx btw

#

im treating bot as a client

#

ctx is the context of the command, which includes information like from who, in what guild, in what channel, etc. the command was executed.

#

ok so i should include a new class for that?

#

!d discord.ext.commands.Context

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

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

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

This is the class containing all the attributes and methods you can use on a ctx parameter.

slate swan
#

ok

tidal hawk
#

Hi, Can there be runnning like 10+ on member join asynchronous functions at the same time? I mean it's async function so it should be

#

But there are some problems with it atm

slate swan
#

Where do I get the on_command_error list?

#
@example.error
async def example_error(self, ctx, error):
  if isinstance(error, ...):
    # code...
fluid spindle
#

Just a quick question: What's the latency that you guys get usually?

slate swan
#

I made a levelling system with my beginner knowledge

slate swan
#

on_command_error

fluid spindle
slate swan
slate swan
#

Check if the message.guild.id is the server ID. If yes, then use get_channel to get the channel and the channel ID as parameter; and then send it again in that channel using .send().

#

Just like above, but compare message.guild.id and message.channel.id with the IDs

#

Then use bot/client.get_channel(the_id), save it as a variable and use .send() on that variable.

tame sierra
#

How do you take in an attached image as a command parameter?

vale wing
#

Slash command?

#

I actually had the same issue, turns out there's no way to provide the image as an argument

#

You may get it if you use common command or message command

true moon
#

This give the error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Select' object is not subscriptable but why?

true moon
vale wing
#

Not really familiar with discord_components but I guess the issue is in res.component[0].label, maybe component is not a list but the select itself?

#

You could put all those ifs into one or into all

#

Also variables names should be in snake_case or smth

slate swan
#

so now i have created my bot and hosted it in replit web server but how can someone add it into their server

true moon
vale wing
#

The res.component

slate swan
#

Would this work? @vale wing

with open(f"./data/users/{ctx.author.id}.json", "r") as f:
vale wing
#

Depends where do you run this from

slate swan
#

when the file is userID.json

slate swan
vale wing
#

@slate swan this doesn't seem quite right

message.guid.id(SecondServer).send(Sc, message.content)```
slate swan
slate swan
#

It works like json

vale wing
#
await client.get_channel(second_channel_id).send(message.content)```
slate swan
#

🥭 db

slate swan
vale wing
#

@slate swan btw you should really use a database rather than to do the things like this. Before I learned how to use a database I did it the same way but with pickle files, got everything corrupted one "beautiful" day

#

Personally I am using sqlite3

slate swan
vale wing
#

Mongodb is like json afaik

true moon
slate swan
#

it works with dictionaries just like json does , difference is that you dont .load or .dump data there , there are different methods

true moon
#

Never mind i got it!

vale wing
#

print is op

#

Better version would be

main_channel = client.get_channel(12345678)
second_channel = client.get_channel(87654321)
if message.author.id == client.user.id and message.channel == main_channel and message.content == 'blah blah blah':
  await second_channel.send(message.content)```

You don't really need to get a guild to get a channel
#

I needed to setup voting rewards for top.gg and discordbotlist.com and build whole API to implement them, did I do the right thing or I could do easier and better?

@api.post('/uservoted')
async def uservoted(request: web.Request):
    if request.headers['Authorization'] !='some token':
        return web.Response(status=403)

    r: dict = await request.json()
    id = int(r.get('id', r.get('user')))
    #some my code that adds voting rewards

    async with ClientSession(**DISCORD_PARAMS) as discord_session:
        channel_id_res = await discord_session.post(
            'https://discord.com/api/v9/users/@me/channels', 
            json={'recipient_id': str(id)})
        channel_id = (await channel_id_res.json())["id"]
        await discord_session.post(
            f'https://discord.com/api/v9/channels/{channel_id}/messages', 
            json={'embeds': [embeds.success('Thanks for Voting!', 'We have sent you the rewards :wink:').to_dict()]})
            
    return web.Response(status=200)```
true moon
#

How can make that only the user who issued the command can use the dropdown menu, buttons or reaction

#

please help cuz i don't know

vale wing
#

In dpy 2.0 there's interaction_check, dunno about discord_components

#

Maybe there's a similar thing

#

@true moon found it

#

Use check param in wait_for

slate swan
#

This is just like waiting for any event dispatch.

true moon
slate swan
#

There are examples in the documentation.

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
vale wing
#

Yeah I just found out, I have no much experience with discord_components

slate swan
#

See the examples there.

slate swan
true moon
#

like This menu is not meant for you

vale wing
#

Oh

slate swan
#

I wouldn't do that.

vale wing
#

Use non lambda function, check the condition and if condition is false, send a message to interaction

slate swan
#

Simply ignoring is the best option. When it will get multiple people to interact randomly then your bot will always send and spam messages.

true moon
#

so like

#
def check(interaction):
  if not interaction.author == ctx.author:
    await interaction.respond('Not meant for you.')
vale wing
#

Yeah but the function must return something

slate swan
#

You can simply add a return before.

vale wing
#

So make sure it returns the valid option

slate swan
#

It doesn't matter.

true moon
#

kk

slate swan
#

Just handle the return correctly with the wait_for.

#

Note that if you do like that, the original user who executed the command won't be able to interact with the drop-down or button.

#

So the best is to ignore invalid users, unless you want to let others block the component for the original user.

true moon
#

Yeah ok

vale wing
#

You don't really need that not lol

true moon
#

ik

#

bruh

vale wing
#

Sorry

true moon
#

ignoring the user gives the This interaction failed error on discord

#

😮‍💨

vale wing
#

Nvm doesn't work for me

#

The only thing I can suggest is use dpy 2.0 or its fork that supports components, might take some time to learn but it still looks better than discord_components

frail notch
#

how to get a guild id out of an invite in python (if possible without the use of importing discord)
so far all i got is the user to input the guild invite

vale wing
#

It is only possible if you make a request to discord API

#

I think

#

Lemme search through their docs

frail notch
#

oh alr

vale wing
frail notch
#

alright..

#

okay thanks

vale wing
#

Just request to that endpoint and get ['guild']['id'] from the response

frail notch
#

alright thanks

slate swan
#

how long can i have a message for ?

frail notch
slate swan
#

stupid way i worded that question

#

just ignore it

velvet tinsel
#

uh ok

slate swan
#

can I execute a command in a command?
so i mean like, a person don't have a profile

@client.command()
async def help(ctx):
  if ctx.author.id in list:
    # help list
  else:
    # execute cmd

@client.command()
async def cmd(ctx):
  # creates a profile
#

or is there a way, my bot create a profile automatically if the user is in the same server?

vale wing
#

I remember there's a way like cmd.__call__(ctx) but I am not sure of this, lemme test

#

@slate swan

@bot.command()
async def cmd1(ctx):
    await ctx.send('Executed cmd1')
    await cmd2(ctx)

@bot.command()
async def cmd2(ctx):
    await ctx.send('Executed cmd2')```
Worked
slate swan
#

ahhh okay

vale wing
#

I guess the difference between just using a command and using __call__ is that call doesn't complete checks

#

Nvm they work the same maybe I should ask someone with higher experience about that

#

Just remember that calling a command from another command will execute it no matter what checks are applied to it

slate swan
#

^^? Would work, right?

vale wing
#

Um

slate swan
#

ah

vale wing
#

You messed names up I think

slate swan
#

now xD

#

Use ctx.invoke

#

!d discord.ext.commands.Context.invoke

unkempt canyonBOT
#

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

Calls a command with the arguments given.

This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.

Note

This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.

You must take care in passing the proper arguments when using this function.
vale wing
#

Obviously there had to be a better method thx

slate swan
#

First argument is the command object that you can get with bot.get_command("name")

#

Then you need to pass all arguments, besides ctx individually.

#

Which results into something like that for the command !userinfo <user>

await ctx.invoke(bot.get_command("userinfo"), user=user)
vale wing
#

@slate swan wait what is this method's advantage above just calling the command func except it can invoke the command from another cog?

slate swan
#

That's the advantage.

vale wing
#

Oh ok

slate swan
#

And I don't even know if calling the function directly works, probably but not sure.

slate swan
#

All right.

vale wing
#

Btw what's the purpose of __call__ I don't get it

slim ibex
#

__call__ lets you create classes where its instances are like functions

foggy zealot
#

how can i make the python eval command?

slate swan
#
x(y=54)
# Same as
x.__call__(y=54)

Considering x is an object.

slim ibex
#

^

vale wing
#

Ok

slim ibex
#
x(y=54)

is shorthand

vale wing
#

I understand that just needed to know what's the difference between just calling and using __call__

#

Seems like there's no much difference

slate swan
#

!e

class Test: 
    def __init__(self):
        print("Instance created...")

    def __call__(self):
        print("Instance is called...")

t = Test()
# __call__ will be called
t()
unkempt canyonBOT
#

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

001 | Instance created...
002 | Instance is called...
vale wing
#

Alright so that thing allows us to call object instances and is a magic method

#

Thx got it

foggy zealot
vale wing
#

See its source code

foggy zealot
#

uh where?

lament mesa
#

!src int e

unkempt canyonBOT
#
Command: internal eval

Run eval in a REPL-like format.

Source Code
spring flax
#

can anyone help with something about disnake. I got some error when i made application commands saying sync commands something

#

and then when I right clicked a message the whole apps part was gone

vale wing
#

Could you show your code?

#

And the exact exception

slate swan
#

and how to language everything? xD

#

Would like to use json too

spring flax
foggy zealot
#
import contextlib
import inspect
import pprint
import re
import textwrap
import traceback
from collections import Counter
from io import StringIO
from typing import Any, Optional, Tuple

import arrow
import discord
from discord.ext.commands import Cog, Context, group, has_any_role, is_owner

from bot.bot import Bot
from bot.constants import DEBUG_MODE, Roles
from bot.log import get_logger
from bot.utils import find_nth_occurrence, send_to_paste_service

@internal_group.command(name='eval', aliases=('e',))
    @has_any_role(Roles.admins, Roles.owners)
    async def eval(self, ctx: Context, *, code: str) -> None:
        """Run eval in a REPL-like format."""
        code = code.strip("`")
        if re.match('py(thon)?\n', code):
            code = "\n".join(code.split("\n")[1:])

        if not re.search(  # Check if it's an expression
                r"^(return|import|for|while|def|class|"
                r"from|exit|[a-zA-Z0-9]+\s*=)", code, re.M) and len(
                    code.split("\n")) == 1:
            code = "_ = " + code

        await self._eval(ctx, code)

so thats all?

vale wing
vale wing
#

Also its a subcommand of internal_group

foggy zealot
#

._. what i have to do?

vale wing
#

Create new command and adapt the code for it

foggy zealot
#

can u modify it as a simple command?

slate swan
foggy zealot
slim ibex
#

database > json

#

but json if your starting prolly

vale wing
slim ibex
#

database isn't that hard

slim ibex
vale wing
foggy zealot
slim ibex
#

??

#

what

vale wing
#

If you don't need to do async actions in your eval you could just use builtin eval btw

vale wing
#

Why tho

slim ibex
#

you mean the builtin python eval()

#

?

vale wing
#

Yeah

#

Without async actions it works fine

#

And like it's not supposed to work with async

foggy zealot
#

look, idk discord.py ok? on school we learn basic python so in order to help my classmates, i wanted to make a bot that evals python codes. The only way is through discord.py that i dont know. thats why i want a simple command only

slim ibex
#

dont use it

slate swan
#

then im doing it in my style

#

mehehe

slim ibex
#

bro

vale wing
slim ibex
# vale wing Yeah

i guess, but you would prolly still have to make a clean code function

foggy zealot
slim ibex
#

you can do it in all python discord api wrappers

foggy zealot
#

bruh

#

discord.js isnt a python module

slim ibex
#

ik

#

idk why i said that

vale wing
#

It is node.js library afaik

slim ibex
#

^

#

i guess i didn't see python eval command even thought it was bold

#

LMFAO

#

anyways, use d.py forks like nextcord or disnake

foggy zealot
#

then how can i eval python codes without using python

spring flax
vale wing
#

@spring flax we need your code

#

Also did you check what that link says?

foggy zealot
#

so how can have the same eval command as here but simple way?

slim ibex
#

all eval commands will be complex

foggy zealot
#

i searched even for a py debugging API bit there arent any

spring flax
rugged marsh
#

eval(\"print("Hello, world?\")")?

foggy zealot
#

!eval("print("Hello, world?")")?

rugged marsh
#

ohhh

#

you want to run python in bot and return output?

#

code from user?

spring flax
#
@bot.message_command(name="Bookmarm Message")
async def bookmark(inter, message):
    embed=disnake.Embed(title="Your Bookmark", color=disnake.Color.blurple())
    message_list = message.content.split()
    joined = " ".join(message_list[:75])
    if len(message_list) > 75:
        short_msg = f"{joined}..."
    else:
        short_msg = joined
    if not message.embeds:
        if not message.attachments:
            embed.description = short_msg
    if message.author.avatar:
        embed.set_author(name=message.author, icon_url=message.author.avatar.url)
    else:
        embed.set_author(name=message.author)
    embed.add_field(name="Message Bookmarked", value=f"[Visit original message]({message.jump_url})")
    embed_to_send = disnake.Embed(description=f"{bot.success_emoji} A bookmark to that message has been sent!")
    await inter.send(embed=embed_to_send, ephemeral=True)
    await inter.author.send(embed=embed)
    ```@vale wing
slim ibex
#

if you want it THAT simple, you would have to pass in a message parameter to the eval and add whatever you need to that

#

or something like that

rugged marsh
#

!e

eval("print("Hello, World!""))
unkempt canyonBOT
#

@rugged marsh :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     eval("print("Hello, World!""))
003 |          ^^^^^^^^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
foggy zealot
#

!eval "print("Hello, world?")")?

unkempt canyonBOT
#

@foggy zealot :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 1
002 |     \"print("Hello, world?\")")?
003 |      ^
004 | SyntaxError: unexpected character after line continuation character
rugged marsh
#

!e

eval("print(\"Hello, World!\")")
unkempt canyonBOT
#

@rugged marsh :white_check_mark: Your eval job has completed with return code 0.

Hello, World!
vale wing
#

@foggy zealot I made a prototype that executes some code you may try it out

import io
import contextlib

def exec_code(code):
    result = io.StringIO()
    with contextlib.redirect_stdout(result):
        exec(code)
    return result.getvalue()```
What it does is just executes your code and returns what it printed
slim ibex
#

!e

fruits = ["apple", "banana", "pear", "strawberries"]
fruits2 = [x for x in fruits if "a" in x]
print(fruits2)
unkempt canyonBOT
#

@slim ibex :white_check_mark: Your eval job has completed with return code 0.

['apple', 'banana', 'pear', 'strawberries']
foggy zealot
#

!eval
import io
import contextlib

def exec_code(code):
result = io.StringIO()
with contextlib.redirect_stdout(result):
exec(code)
return result.getvalue()

unkempt canyonBOT
#

@foggy zealot :warning: Your eval job has completed with return code 0.

[No output]
foggy zealot
#

hmm

slim ibex
#

bru

foggy zealot
#

i forgot to add some text

vale wing
#

Execute it in your IDE or smth

#

It will block the execution most likely

slim ibex
#

!e

x = True
y = 10 if x else 0

print(y)
unkempt canyonBOT
#

@slim ibex :white_check_mark: Your eval job has completed with return code 0.

10
vale wing
#

!e

import contextlib, io

def exec_code(code):
    result = io.StringIO()
    with contextlib.redirect_stdout(result):
        exec(code)
    return result.getvalue()

exec_code('for i in range(5): print(i)')```
unkempt canyonBOT
#

@vale wing :warning: Your eval job has completed with return code 0.

[No output]
vale wing
#

Yeah it blocks it

rugged marsh
#

!e

import contextlib, io

def exec_code(code):
    result = io.StringIO()
    with contextlib.redirect_stdout(result):
        exec(code)
    return result.getvalue()

print(exec_code('for i in range(5): print(i)'))```
vale wing
#

Nvm I forgot to print the result

unkempt canyonBOT
#

@rugged marsh :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
rugged marsh
#

nope, you didn't print it

vale wing
rugged marsh
#

lol

foggy zealot
slim ibex
#

phone coding

#

new meta

vale wing
#

😳 phone coding

foggy zealot
slim ibex
#

this dude has ascended humanity

vale wing
#

I used to code on phone as well

rugged marsh
#

but exec() command has a side effect, it could modify a global variable, might be dangerous

vale wing
#

Maybe we can do something to its globals param?

foggy zealot
rugged marsh
#

make variables hard to guess :)

silver magnet
#
async def on_message(message):
    if message.user == "hello":
        await message.send("hi")```
im trying to make triggers but i only started with python 2 days ago
this is probably totally wrong
vale wing
#

Don't think there's user attribute for message

rugged marsh
#

or create a temp file, and execute it, catch output and return using subprocess

vale wing
#

Depends on library

vale wing
#

!d discord.Message.content

unkempt canyonBOT
vale wing
#

Damn I should really update my exec commands for bots lmao

silver magnet
rugged marsh
#
@client.event
async def on_message(message):
    if message.content == "hello":
        await message.send("hi")```
silver magnet
#

i tried that

#

doesnt seem to work, weird

rugged marsh
#

are you new to python?

silver magnet
#

very

#

started like 2 days ago

slim ibex
#

discord bot isnt a good beginner prject

rugged marsh
#

go learn something else :)

silver magnet
#

okay

spring flax
heavy folio
#

how do i unviewlock a thread for a member

  • unviewlock meaning it's redTick for the everyone role, then editing the perms to greenTick for a specific member
spring flax
heavy folio
spring flax
#

!resources

unkempt canyonBOT
#
Resources

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

rugged marsh
#

ok ;-;

#

anyone has a good example of asynchronous and synchronous?

spring flax
#

it's message.channel.send*

unkempt canyonBOT
#

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

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

import discord

# Bunch of bot code

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

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

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

rugged marsh
#

trying to explain it to my friend ;-;

foggy zealot
#

rip the eval command._.

heavy folio
#

what happened

vale wing
heavy folio
#

actually i didnt see the add_user() method

#

got it

vale wing
#

Ok

foggy zealot
vale wing
#

I just made it lol

foggy zealot
#

where

vale wing
#

You just gotta embed the function I made into a command

foggy zealot
#

well i dont know that too xd

vale wing
#

Um just call the function from a command?

foggy zealot
#

idk how to make awaited delete command with bin emoji reaction

vale wing
#

Oh awaited

foggy zealot
#

exactly how it is here

#

something like: onReactionAdd($deleteMessage) idk

frail notch
#

pepeSad can someone explain to me how to fix this
the code is

#turn server invite into guild ID
def guild_id(guild_invite):
    url2 = f"{API_ENDPOINT}/invites/{guild_invite}"
    response = requests.get(url2)
    data = response.json()
    guild_id = data["guild"]["id"]
vale wing
#

Ah so you only want it to delete the message if you press the reaction?

#

You don't need to execute asynchronous codes?

vale wing
#

Why would you need to call a str like fr

foggy zealot
frail notch
#

oh

#

soz

vale wing
#

@foggy zealot so let's state what do you want your command to do and like use an example

#

Like I made my command to be like this

foggy zealot
#

i want it to work just like the bot here if possible

vale wing
#

Not as good as python's but simplier

foggy zealot
#

oh and... can it count lines? 001, 002....?

vale wing
#

That's up to you and is decorative

foggy zealot
#

i have no idea how to do it

vale wing
#

@foggy zealot one question, when did you start learning python?

slim ibex
#

you shouldn't be trying to make an eval command, whihc is advanced, if you dont even know d.py basics

foggy zealot
#

on school this year, basic stuff, not discord related

slim ibex
#

whats basic stuff

vale wing
#

Just saying that discord bot is typically an asynchronous app and it is very advanced

slim ibex
#

^

vale wing
#

Maybe you need to complete a discord bot tutorial first

#

Tho dpy is no longer being maintained

foggy zealot
#

i know discord.js

vale wing
#

They have similarities but they are different, they have different languages

foggy zealot
#

and when i say basic stuff, i mean prints if, while, for, imports, inputs, and defs

#

thats all i know ._.

vale wing
#

What about classes

foggy zealot
#

not yet

slim ibex
#

classes/OOP are important to d.py

vale wing
#

Decorators?

foggy zealot
#

nothing else

#

i learnt threading by myself

vale wing
#

I think you can learn dpy with your current experience, but you need to learn more about classes and maybe decorators, also the tutorial I sent to you is very helpful 😉

slate swan
#

It's not about learning discord.py; it's about learning Python and being a able to use it while reading the documentation of discord.py

foggy zealot
#

but all i want from d.py is a command ._.

slim ibex
#

and that command requires some intermediate python knowledge

vale wing
#

You want uh kinda complicated command

foggy zealot
#

i know how to do it in js

#

but it evals js codes lemon_unamused

vale wing
#

I am pretty sure js has libraries for evaluating python codes

foggy zealot
#

umm nope

vale wing
#

Like java does for sure

foggy zealot
#

i have searched even APIs that return python codes

slate swan
#

You should use a sandbox for eval command though.

slate swan
foggy zealot
#

whas a sandbox?

vale wing
#

Js should have as well

foggy zealot
slate swan
#

discord.js is not a language.

#

It's a library.

slim ibex
#

Discord.JavaScript

foggy zealot
#

yes

slate swan
#

So anything that can be used in JS can be used with discord.js

foggy zealot
#

OH so i can code bots in whole plain language?

slim ibex
#

you use JS in discord.js, you use python in discord.py

foggy zealot
#

i didnt know that

vale wing
#

@foggy zealot I just searched for libraries, there's something like py.js

#

Maybe that's what you need

foggy zealot
vast gale
#

imagine not making a meta discord bot

foggy zealot
#

the name is cringe but alr imma study it lol

vast gale
#

I have sadly made a bot to help make bots

#

please save me from myself

vale wing
#

I really want to make a bot for hosting bots but need to think out much of stuff

slow furnace
#

hey guys, sorry to cut in, has anyone got any idea for dropbox token here for discord bot?

vast gale
#

wdym?

slow furnace
slow furnace
slow furnace
vale wing
#

Also need to add protection against "too smart" bot coders that would want to break the server Thonk

slate swan
#

And you want to do exactly the same 2DkizunaWhat

vast gale
#

although...

#

oh that makes me wonder

vale wing
#

If they put os.system('reboot') it might reboot the server lmao not sure tho

#

Maybe I need some kind of venv?

vast gale
#

so @unkempt canyon' eval command exists

vale wing
#

Nono I mean like bot for hosting bots

#

For example, you upload source code to github, the bot loads it to some directory and executes

vast gale
#

that makes me wonder... could you do something with the already existing sandbox for processes and give them network access

vale wing
#

But it should filter malicious code

vast gale
#

eg someone could run os system reboot and no problems

vale wing
#

I really need to figure that out

vast gale
#

my bot is essentially python + lance mixed into one bot, made extreme python and development focused, and then slash commands

slate swan
#

How do I get the username + discriminator / tag, only by the id?

vast gale
#

!d discord.Client.fetch_user

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.get_user "discord.Client.get_user") instead.
slate swan
#

I tried

user = userID
ctx.send(f"{user.name}")
slate swan
slate swan
unkempt canyonBOT
honest shoal
#

I'm having a problem with disnake, member.status shows false status

slate swan
# slate swan ty

Not recommended at all, use bot.get_user(id) or await bot.fetch_user(id)

vast gale
# slate swan ty

although it's best to pair that with an attempt to get it from the cache with what @slate swan said

vale wing
#

Both in dev portal and in code

vast gale
#

I figured you had only a user ID, but given what you're sending it should be cached 🙃

slate swan
#

you can just use ```py
user = bot.get_user(id) or await bot.fetch_user(id)

slate swan
#

disnake already made a handy method

vast gale
slate swan
#

!d disnake.Client.get_or_fetch_user

unkempt canyonBOT
#

await get_or_fetch_user(user_id, *, strict=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.
vast gale
unkempt canyonBOT
#

await getch_user(user_id, *, strict=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Tries to get the user from the cache. If fails, it tries to fetch the user from the API.
slate swan
#

is same

vast gale
#

ye

slim ibex
#

getch_user?

slate swan
#

🏃‍♂️ ty for saving me from hitting the _ 4 times

vale wing
#

Funny name

slim ibex
#

get+catch user?

vast gale
#

getch--get or fetch

slim ibex
#

clever

honest shoal
slate swan
honest shoal
slate swan
#

ow , does it always show that the user is offline?

honest shoal
vast gale
#

🤔

#

do you have the precenses intent?

slate swan
honest shoal
#

precenses intent?

honest shoal
vast gale
#

yes, you need an intent to view if members are online

honest shoal
#

the Default one is enabled

slate swan
#

not the default ones

honest shoal
#

disnake.Intents.default()

slate swan
#

its a privelaged intent

honest shoal
#

ohh

#

where can I find it

#

!d disnake.Intents.presences

unkempt canyonBOT
#

Whether guild presence related events are enabled.

This corresponds to the following events:

on_presence_update()

This also corresponds to the following attributes and classes in terms of cache...

slate swan
#

its not documented

vast gale
#

yes

#

I can't spell

slate swan
#

ah

honest shoal
#

I asked in disnake server too but don't know who deleted my message

vast gale
#

I never saw it 💀

silver magnet
#

what's an object i could use to replace message.author but that doesn't mention the user's tag? i looked through the discord.py documentation already.

vast gale
silver magnet
#

thanks

frail notch
#

Why does it not output the guild id?

slate swan
#

Hey

potent spear
slate swan
#
description=f"<a ![thumb](https://cdn.discordapp.com/emojis/853182969618366464.webp?size=128 "thumb")  Changed roles for {member.name}, +{ctx.role.name}") 

Can you tell me what's the problem here

maiden fable
#

U meant a:

frail notch
potent spear
frail notch
#

Oh... lmao

slate swan
#
description=f"Changed roles for {member.name}, +{ctx.role.name}"

Can you tell me what's the problem here

#

It doesn't send embed

potent spear
#

unless it's in an embed and you're not showing everything ofc

slate swan
#
description=f"Changed roles for {member.name}, +{ctx.role.name}"

Can you tell me what's the problem here

frail notch
#

thinkFish how can i fix dis

slate swan
#

Under Curly brackets

potent spear
potent spear
potent spear
frail notch
#

wait nvm

#

yea i do

slate swan
#
#**__Role__**
@client.command()
@commands.has_role(922058791510474822)
async def role(ctx,member:discord.Member, role : discord.Role):
    await member.add_roles(role)
    embed=discord.Embed(colour=discord.Colour.red(),description=f"<a![thumb](https://cdn.discordapp.com/emojis/853182969618366464.webp?size=128 "thumb")853182969618366464> Changed roles for {member.name}, +{ctx.role.name}")
    await ctx.send(embed=embed)

Don't mind the emoji id. It's discord bug. Can you tell me the problem in member name and role name because it doesn't send embed

#

Indentation is wrong.

#

Nope

potent spear
slate swan
#

Right, mobile is broken. Look your console.

#

It shows this

#

Remove ctx.

potent spear
slate swan
#

After the "+"

frail notch
#

How do I fix this error...?

maiden fable
silver magnet
#

how do i make the bot find out that the message author is itself?

maiden fable
#

!d discord.Client.user

unkempt canyonBOT
#

property user: Optional[discord.user.ClientUser]```
Represents the connected client. `None` if not logged in.
elfin oxide
#

/help

#

wtf

maiden fable
#

Wrong Server My Man

slate swan
#

You probably want data["guild"]["id"]

finite cobalt
#

is it possible to detect if a user is currently muted in a vc

slate swan
#

You should make the request yourself, then you see how the JSON looks like. Here is an example:

{
   "code":"pVGHD65s",
   "type":0,
   "expires_at":"2022-01-16T14:55:13+00:00",
   "guild":{
      "id":"911613911315382332",
      "name":"kekkers",
      "splash":null,
      "banner":null,
      "description":null,
      "icon":null,
      "features":[
         
      ],
      "verification_level":0,
      "vanity_url_code":null,
      "nsfw":false,
      "nsfw_level":0
   },
   "channel":{
      "id":"915237808430526474",
      "name":"general",
      "type":0
   },
   "inviter":{
      "id":"562359123086409729",
      "username":"Krypton",
      "avatar":"dde9020f2166f7016b4496757e264f98",
      "discriminator":"7331",
      "public_flags":131136
   }
}
slate swan
unkempt canyonBOT
slate swan
#

Also this in case the user is muted on the entire guild.

#

!d discord.VoiceState.mute

unkempt canyonBOT
finite cobalt
#

ok thanks

slate swan
#

And to get the VoiceState object it's simply the voice attribute on a discord.Member object.

silver magnet
#

trying to make these triggers case insensitive, any way how?

async def on_message(message):
    if message.author == client.user:
        return
    else:
        if message.content == "hello":
            await message.channel.send(f"hello {message.author.name}!")
        elif message.content == "hi":
            await message.channel.send(f"hello {message.author.name}!")
        elif message.content == "bye":
            await message.channel.send(f"goodbye {message.author.name}!")
        elif message.content == "goodbye":
            await message.channel.send(f"goodbye {message.author.name}!")```
finite cobalt
#

And how do i check all the time if hes muted?

slate swan
#

You don't need to check all the time

finite cobalt
#

do i need to make a @client.event?

slate swan
#

!d discord.on_voice_state_update

unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
slate swan
#

That's some very basic Python :p

silver magnet
#

yeah im just new

slate swan
#

Then you should consider learning more, as this is one of the first things you will learn.

#

!resources Can help

unkempt canyonBOT
#
Resources

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

cerulean lichen
#

Hi guys!
Simple question, I have couple tasks that I need to check for updates every second and then the bot should respond.
Do I need a bot for each task? or I can use the async functions and that will work?

finite cobalt
finite cobalt
#

So i want to check if a user is muted how do i do that

cerulean lichen
slate swan
cerulean lichen
#

ok cool, thnx 🙂

slate swan
# finite cobalt So i want to check if a user is muted how do i do that

Come on, that's very simple after what I've said:

• To get a VoiceState, use the voice attribute on a Member object.

voice_state = ctx.author.voice

• To check if the user is muted, you can use the mute or self_mute attribute on a VoiceState object:

muted_or_not = voice_state.mute or voice_state.self_mute
finite cobalt
#
async def on_voice_state_update(ctx):
    voice_state = ctx.author.voice
    if voice_state.self_mute == True:
        print("true")```
#

so if have this but its not working

slate swan
#

Remove == True

#

!d discord.on_voice_state_update

unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
slate swan
#

As you can see, it takes 3 parameters and no ctx parameters.

#

member, before, after

finite cobalt
#

yes

slate swan
#

Then don't use ctx but those.

finite cobalt
#

but then its an error with voice_state = ctx.author.voice

slate swan
#

Now you know what each parameter represents, you can fix it yourself.

finite cobalt
#
async def on_voice_state_update(member, before, after):
    voice_state = member.author.voice
    if voice_state.self_mute:
        print("true")```
#

like this??

slate swan
#

Well, as you can see the before and after parameters are of type VoiceState.

#

One before they changed it and one after they changed it.

#

Choose which one you need to use.

finite cobalt
#

But the voice_state = membe.author.voice is not working

slate swan
silver magnet
#
async def ping(ctx):
    await ctx.channel.send(f"In milliseconds: {round(client.latency * 1000)}")```
this command used to work but it just stopped working.
finite cobalt
#

I dont get it

slate swan
#

member.voice is the same type as before and after

finite cobalt
slate swan
#

Now choose if you want to check the voice state before or after they changed it.

slate swan
silver magnet
#

when i did (prefix)ping it sent the ping without any flaws, now it just doesn't give any response at all, not even errors

slate swan
#

But your bot starts correctly?

silver magnet
#

yeah

slate swan
#

May you share more code? Issue is probably somewhere else.

#

on_message event . do you have one?

finite cobalt
#

How can i get a voice channel by its id?

silver magnet
# slate swan May you share more code? Issue is probably somewhere else.

its probably very bad because im still learning as you might know
||```import discord
from discord.ext import commands

print(discord.version)

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

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

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

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

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

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

client.run(TOKEN)```
||

slate swan
#

Use get_channel

slate swan
silver magnet
#

now it works

slate swan
#

Glad to hear that beergopher

#

My bot is unable to delete its own messages

#
await message.delete()
#

It always is able to delete its own messages.

#

You'd need to give more code than just that :p

finite cobalt
#
            print(member)```its just printing one member
slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

Enable the members intent in code and developer portal.

#

but as per logic shouldn't it delete its own code

#

How to install this?

#
 msg = message.content
  if not msg.startswith("$") and message.channel.name == "word-chain":
       if msg.lower() not in wordlist:
            wordlist.append(msg.lower())
       elif msg.lower() in wordlist:
           await message.channel.send("You already said that word!")
           await message.delete()
await message.delete()

slate swan
unkempt canyonBOT
slate swan
slate swan
#

but if i delete message 2 times , it should delete its own message ri8?

#

No

#

why

#

!e
x = 1
print(x)
print(x)

unkempt canyonBOT
#

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

001 | 1
002 | 1
slate swan
#

It never changes :p

#

It's a variable, it never changes unless you change it by yourself, which you never did.

#

ic

#

If you want the bot to delete a message the bot sent, you need to create a new variable when sending the message and use .delete() on that one.

#

Something like this:

x = await message.channel.send(...)
await x.delete()
#

ok

honest vessel
#

is there a way to see who deleted a msg if it was themselfs or a mod?

slate swan
#

One thing that can help you are the audit logs.

honest vessel
silver magnet
#

What's the object i need to make a bot add reactions?

slate swan
#

Depends how you want to manipulate the message later.

honest vessel
#

@slate swani was thinking in the event on_message_delete

slate swan
#

Error says all

frail notch
#

xD

slate swan
#

You are giving a function instead of a snowflake as value.

frail notch
#

just notices

silver magnet
slate swan
#

await

silver magnet
#

i used await too

astral mountain
#

how do you get a bot to send imported python files into a channel ?

slate swan
silver magnet
#

👍

slate swan
#

:something:?

silver magnet
#

:thumbsup:

slate swan
#

You need to use a raw emoji, such as \👍

silver magnet
#

i tried the raw emote p sure

slate swan
#

Add a \ before sending it and copy paste that.

silver magnet
#

oh

slate swan
astral mountain
slate swan
#

What are you trying to do?

astral mountain
#

I am trying to crate a leveling system

#

or a base

slate swan
#

Why would you need to send all imported files in a channel for that?

honest vessel
#
>>> import time
>>> import sys
>>> print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'time': <module 'time' (built-in)>, 'sys': <module 'sys' (built-in)>}
astral mountain
#

@slate swan I have two files the game itself and the bot and i wanted to combine them using that function

maiden fable
#

Python sadcat

silver magnet
slate swan
#

What is your code now?

silver magnet
#

full or just the @client.command of the poll feature?

slate swan
#

Where you add the reaction of course ^^

silver magnet
#

await message.add_reaction("\👍")

#

anywhere else it gives an error

slate swan
#

No \

#

When you send in chat use that, then copy paste what got sent.

#

\👍

#

This needs to be copy pasted.

silver magnet
#

do i need to place <> around the emote?

slate swan
#

No

slate swan
silver magnet
#

there's apparently something wrong in if message.author == client.user:

slate swan
#

Such as?

silver magnet
#

AttributeError: 'str' object has no attribute 'author'

slate swan
#

Why did you replaced the message variable to a string?