#discord-bots
1 messages · Page 737 of 1
do any of yall know how to stop an asyncio command from running?
return
returns a function and stops the function
like an asyncio.sleep command
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
My bot has the same pfp as you do wow
overused
Oh that’s interesting
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.
heroku does not allow you to change any files , it reverts back to its original condition
Oh ok
Is there any way I can make this possible?
I'll probably try PostgreSQL
I need a database for economy
sure , if you want it to stay json like , use mongodb
!pypi motor
oh that'd be great.
thanks..
That won't work since heroku restarts the state of the machine basically
You'd have to get a database hosted not on heroku
Unless heroku has an addon that supports postgres
a postgres db server maybe?
So as long as it isn't hosted on heroku
it does I read somewhere
Then you'd have to use that
Just pay for him andy
A regular postgres server on heroku would just reset the data after a restart
You are quite rich
I'll surely look into mongodb tho.. I'd like to keep it similar to json
can you show me an example?
if value == "something":
return
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?
what does the return statement do?
!return
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
can you no longer read message contents of others when using on_message?
yes you can
thanks
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
can anyone help me with this? please
@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```
nvm i don't use on_member_update ive actuallynever used it
the issue here is that the code doesn't get processed after printing initiated 1/2
what are you trying to do here?
giving a role for certain game when any player starts or ends the game
Ok
like if I start game1 then the bot will give me game1 role and when I stop it, it will remove that role
how do you start the game1?
no no, I mean the bot reads from the user's activity
Oh got it
here
idk how to fix it tho as i've never used on_member_update
the bot reads the activity, prints initiated 1/2 according to the status but does not assign roles
I think I made a mistake around getting the role
for getting the role
what should I do for it?
try using
get_role = discord.utils.get(ctx.guild.roles, name="role name")
wait a fucking second... ive never used on_member_update but do you have a Member object in that event?
yup, we can use before/after as member object
ctx, guild not defined
add ctx to the function
let me try that
stuff dont work like that lmao
I think it takes 2 arguments only
on_member_update has no context
welp I am new to discord.py
oh! then try doing guild = after.guild and then do v = guild.get_role(<id or namestring here>)
and only takes 2 positional arguments iirc
yup, that's true
nvm im stupid
!d discord.on_member_update
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...
see ^
@exotic patrol try this
actually don't since it doesn't exist 😭
let me try
that's another way of "fetching" the role
how would that work?
yes I tried that too but its the same, I think I had made some syntax error there, so you can send your code and I can try it out
but i remember i used that before ¯_(ツ)_/¯
after is a member obj which member doesnt have a guild attr?
probably in commands
I am doing commands rn... events just too hard for me atm
on_member_update is a event not a command
I know that
🤔 but istg i remember that i used guild.get_role()
not sure what you ment
¯_(ツ)_/¯
I think it was ctx.guild.get_role()
prob
what events exactly
most events are pretty easy
found it!
istg i think it worked
I'll get back and say if it worked or not because I made this bot for valorant only and I have to wait until someone from the whole server starts the game...
alr
🤝
I did not really start events.
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
ic gl
you forgot () in the decorator
@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 = mins60)
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}!')```
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'
oh
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)```
yes
insted of client.run
but i m storing that in variable
you have stored ur token in an environment right
yes
thats why u importedf os
in the first place
im doing that already
u dont just do client.run
oh wait
did u do client.run(ahwhdaiwduawd)
@slate swan
nope
this is my code
it’s an error in your class or object
i haven't created my own class yet
its the default discord classes
object then and it’s returning none
@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
what’s the error
no error
when i run the command just doesnt respond
the bot just doesnt respond to !gstart
my prefix is !
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.
@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
Use pop Instead of remove
Nvm that won't work
Do you have an error handler?
@frank tartan u r adding and removing user IDs, but in the dm command, checking the member object
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??
you can convert other time units to seconds
and it accepts datetime object too
!d disnake.Member.timeout
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.
yea there is one datetime.timedelta but I am not at all familiar with it
that will require another parameter which I want to avoid
!d datetime.timedelta
No idea how it works
its basically a difference between two datetime objects
any example for it?
!pypi humanize
@honest shoal u can use this too
oh, let me see

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
well a tried a time converter but still it was accepting as seconds
, 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}")
if time is none
And how u invoking the cmd?
prefix command
The whole invocation
Command is working properly it times out the user but in seconds
so there's problem with time converter
Try printing timeout_time
When I run it from my pc it works fine, but from the host it doesn't
Wait, so on heroku u did 1m as timeout?
Make sure you've updated the build on Heroku.
Hmm seems more of a code updation problem rather than the logic/code problem
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
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.
when I tried 19m it took as 60 only
oh yea 1m = 60 s
Ah, so u can use slicing
@slate swan :white_check_mark: Your eval job has completed with return code 0.
653
Instead of a timeout time of time[0]
help me for random number command
Thanks @maiden fable @slate swan!
please help=(
what happened?
explain the behavior of command
and what u have made rn + the error ^^
example: [prefix]random 100 => random from 1 to 100
not sure then
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.
ty
@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
on_member_join takes no ctx augment, only a member argument and that's it.
isnt range a python keyword?
ctx.guild.roles is not working then
You can access the guild object with member.guild instead of ctx.guild.
!d discord.Member.guild
The guild that the member belongs to.
hey anybody here?
would that work @slate swan
@green bluff how can i make function that will work only in a specific channel
like if channel.name == "word-chain":
ok np
Yes it is (Python Function)
IPAy can u help me with this?
Simply replace ctx.guild with member.guild, and remove the ctx parameter.
yep thanks
!custom-check
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.
You should use channel IDs as they will never change, unlike names.
if channel.id == 123:
how can find that id in setting?
Or this, yea
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.
Where do I start?
Wdym
By learning Python and then https://discordpy.readthedocs.io/en/stable/quickstart.html
Then the quick start is where you should go.
okay ty
Then simply go on by reading the documentation for things you want to do and you're good to go.
no
thanks
Any IDE or text/code editor like VSC is fine.
okay
AttributeError: 'TextChannel' object has no attribute 'delete_message'
how can i delete the message by a user
message.channel.delete_message isn't working
await message.delete()
channel.delete_message is like 5 years out of date now
no
i want to delete a specific message , can i give the arguement?
await ctx.message.delete()
?
like i want to delete the message that triggred this command
Then that would be await ctx.message.delete()
ok
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()
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
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.
This is the class containing all the attributes and methods you can use on a ctx parameter.
No, it's automatically done. What you can do is type hint ctx to the class above.
ok
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
Yes, that's the point of an asynchronous library and function.
Where do I get the on_command_error list?
@example.error
async def example_error(self, ctx, error):
if isinstance(error, ...):
# code...
Just a quick question: What's the latency that you guys get usually?
Discord websocket
I made a levelling system with my beginner knowledge
40-60ms
Thats an event
on_command_error
Okay, mine is good to go then...
that answer was useleses
Lol idk wut u meant by "where do i get the ..."
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.
How do you take in an attached image as a command parameter?
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
This give the error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'Select' object is not subscriptable but why?
What library are you using?
discord and discord_components
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
so now i have created my bot and hosted it in replit web server but how can someone add it into their server
I tried the other way but it still gives the same error
Try printing it
The res.component
Would this work? @vale wing
with open(f"./data/users/{ctx.author.id}.json", "r") as f:
Depends where do you run this from
or should i send the url to add it in servers?
when the file is userID.json
What do you mean?
Why dont u use database?
@slate swan this doesn't seem quite right
message.guid.id(SecondServer).send(Sc, message.content)```
do you have a example?
await client.get_channel(second_channel_id).send(message.content)```
🥭 db

@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
nah, i still want to work with json ^^
Mongodb is like json afaik
I tried printing res.component but it gives <discord_components.component.Select object at 0x000001E5E46F51C0> now what should i do?
it works with dictionaries just like json does , difference is that you dont .load or .dump data there , there are different methods
:3
Never mind i got it!
Yeah and you are trying to to Select[0] that's why it raises an error
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)```
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
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
This is just like waiting for any event dispatch.
ik
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**...
Yeah I just found out, I have no much experience with discord_components
See the examples there.
This is the same for discord.py and all other similar libraries, has nothing to do with discord_components.
So you figured it out?
Yeah Smol problem, i used check but how i can respond to user who is not supposed to use this menu
like This menu is not meant for you
Oh
I wouldn't do that.
Use non lambda function, check the condition and if condition is false, send a message to interaction
Simply ignoring is the best option. When it will get multiple people to interact randomly then your bot will always send and spam messages.
so like
def check(interaction):
if not interaction.author == ctx.author:
await interaction.respond('Not meant for you.')
Yeah but the function must return something
You can simply add a return before.
So make sure it returns the valid option
It doesn't matter.
kk
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.
Yeah ok
Btw != is a thing
You don't really need that not lol
Sorry
Lemme test that thing rq
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
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
It is only possible if you make a request to discord API
I think
Lemme search through their docs
oh alr
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Just request to that endpoint and get ['guild']['id'] from the response
alright thanks
how long can i have a message for ?
wdym
uh ok
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?
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
ahhh okay
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
@bot.command()
async def help(ctx):
if ctx.author.id in list
# shows help
else:
await cmd1(ctx)
@bot.command()
async def cmd1(ctx):
# creates profile
await help(ctx)
^^? Would work, right?
Um
ah
You messed names up I think
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.
Obviously there had to be a better method thx
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)
@slate swan wait what is this method's advantage above just calling the command func except it can invoke the command from another cog?
That's the advantage.
Oh ok
And I don't even know if calling the function directly works, probably but not sure.
I just tested, it worked fine
All right.
Btw what's the purpose of __call__ I don't get it
__call__ lets you create classes where its instances are like functions
how can i make the python eval command?
x(y=54)
# Same as
x.__call__(y=54)
Considering x is an object.
^
Ok
x(y=54)
is shorthand
I understand that just needed to know what's the difference between just calling and using __call__
Seems like there's no much difference
!e
class Test:
def __init__(self):
print("Instance created...")
def __call__(self):
print("Instance is called...")
t = Test()
# __call__ will be called
t()
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | Instance created...
002 | Instance is called...
Alright so that thing allows us to call object instances and is a magic method
Thx got it
how can i make this eval code like this?
See its source code
uh where?
!src int e
Run eval in a REPL-like format.
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
This is the message
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?
I heard people recommend creating language database not json
The command is made for cog and you are using it outside the cog
Also its a subcommand of internal_group
._. what i have to do?
Create new command and adapt the code for it
can u modify it as a simple command?
I don't want to use a database :')
Yeah, you also need to bring self._eval to your code
database isn't that hard
there are other things that go into this command. and copying it from this won't make you learn anything
Trust me if your bot grows up you will experience serious issues with those jsons
im not planning go learn d.py, i just wanted the eval command because i csnt use it on other discord coding language
If you don't need to do async actions in your eval you could just use builtin eval btw
not recommended doh
Why tho
Yeah
Without async actions it works fine
And like it's not supposed to work with async
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
I don't use one.
bro
Just to eval not async codes you only need builtin exec and some magic stuff about redirecting its output I am not familiar with
i guess, but you would prolly still have to make a clean code function
how can i make a python eval command without discord.py then mate
you can do it in all python discord api wrappers
It is node.js library afaik
^
i guess i didn't see python eval command even thought it was bold
LMFAO
anyways, use d.py forks like nextcord or disnake
then how can i eval python codes without using python
oh lol
Anyone?
so how can have the same eval command as here but simple way?
all eval commands will be complex
i searched even for a py debugging API bit there arent any
my main question is why it keeps removing the commands from appa here's the code:
eval(\"print("Hello, world?\")")?
!eval("print("Hello, world?")")?
@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
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
!e
eval("print("Hello, World!""))
@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?
!eval "print("Hello, world?")")?
@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
!e
eval("print(\"Hello, World!\")")
@rugged marsh :white_check_mark: Your eval job has completed with return code 0.
Hello, World!
@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
!e
fruits = ["apple", "banana", "pear", "strawberries"]
fruits2 = [x for x in fruits if "a" in x]
print(fruits2)
@slim ibex :white_check_mark: Your eval job has completed with return code 0.
['apple', 'banana', 'pear', 'strawberries']
!eval
import io
import contextlib
def exec_code(code):
result = io.StringIO()
with contextlib.redirect_stdout(result):
exec(code)
return result.getvalue()
@foggy zealot :warning: Your eval job has completed with return code 0.
[No output]
hmm
bru
i forgot to add some text
!e
x = True
y = 10 if x else 0
print(y)
@slim ibex :white_check_mark: Your eval job has completed with return code 0.
10
!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)')```
@vale wing :warning: Your eval job has completed with return code 0.
[No output]
Yeah it blocks it
!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)'))```
Nvm I forgot to print the result
@rugged marsh :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
nope, you didn't print it
Yes I just realized lol
lol
😳 phone coding
im not home lol
this dude has ascended humanity
I used to code on phone as well
but exec() command has a side effect, it could modify a global variable, might be dangerous
Maybe we can do something to its globals param?

make variables hard to guess :)
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
Don't think there's user attribute for message
or create a temp file, and execute it, catch output and return using subprocess
Depends on library
To access message's content, use content attribute: message.content
!d discord.Message.content
The actual contents of the message.
Damn I should really update my exec commands for bots lmao
where do i need to place it? im still new to this stuff sorry
@client.event
async def on_message(message):
if message.content == "hello":
await message.send("hi")```
are you new to python?
discord bot isnt a good beginner prject
go learn something else :)
okay
Don't say that why would you?
how do i unviewlock a thread for a member
- unviewlock meaning it's
for the everyone role, then editing the perms to
for a specific member
Seems you can start with the basics. A in depth guide can be found below.
now spoon feeding wont help others learn :)
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
that is wrong
it's message.channel.send*
!blocking
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!
^
trying to explain it to my friend ;-;
rip the eval command._.
what happened
What library
What happened to it
Ok
i mean no one knows how to make it ._.
I just made it lol
where
You just gotta embed the function I made into a command
well i dont know that too xd
Um just call the function from a command?
idk how to make awaited delete command with bin emoji reaction
Oh awaited
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"]
Ah so you only want it to delete the message if you press the reaction?
You don't need to execute asynchronous codes?
Um maybe you meant
guild_invite = input('Guild invite> ')```?
Why would you need to call a str like fr
mhm
@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
i want it to work just like the bot here if possible
Not as good as python's but simplier
oh and... can it count lines? 001, 002....?
That's up to you and is decorative
@foggy zealot one question, when did you start learning python?
you shouldn't be trying to make an eval command, whihc is advanced, if you dont even know d.py basics
on school this year, basic stuff, not discord related
whats basic stuff
Just saying that discord bot is typically an asynchronous app and it is very advanced
^
Maybe you need to complete a discord bot tutorial first
https://tutorial.vcokltfre.dev/ is a good one
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Tho dpy is no longer being maintained
i know discord.js
It's not discord.py tho
They have similarities but they are different, they have different languages
and when i say basic stuff, i mean prints if, while, for, imports, inputs, and defs
thats all i know ._.
What about classes
not yet
Decorators?
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 😉
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
and that command requires some intermediate python knowledge
You want uh kinda complicated command
I am pretty sure js has libraries for evaluating python codes
umm nope
Like java does for sure
i have searched even APIs that return python codes
You should use a sandbox for eval command though.
In JS you can evaluate Python code, yes.
whas a sandbox?
Js should have as well
available on djs?
Discord.JavaScript
yes
So anything that can be used in JS can be used with discord.js
OH so i can code bots in whole plain language?
you use JS in discord.js, you use python in discord.py
i didnt know that
@foggy zealot I just searched for libraries, there's something like py.js
Maybe that's what you need

imagine not making a meta discord bot
the name is cringe but alr imma study it lol
I really want to make a bot for hosting bots but need to think out much of stuff
hey guys, sorry to cut in, has anyone got any idea for dropbox token here for discord bot?
wdym?
so something like this
https://stackoverflow.com/questions/70641660/how-do-you-get-and-use-a-refresh-token-for-the-dropbox-api-python-3-x
yeah that sounds complicated
You asked that question?
someone else did
but i have the same question in mind
Also need to add protection against "too smart" bot coders that would want to break the server 
probably would get a better answer in #python-discussion or see #❓|how-to-get-help
And you want to do exactly the same 
ok cool cool. thank you!
too smart
literally an eval command smh
although...
oh that makes me wonder
If they put os.system('reboot') it might reboot the server lmao not sure tho
Maybe I need some kind of venv?
so @unkempt canyon' eval command exists
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
that makes me wonder... could you do something with the already existing sandbox for processes and give them network access
But it should filter malicious code
yes, but the backend is open source
eg someone could run os system reboot and no problems
I really need to figure that out
my bot is essentially python + lance mixed into one bot, made extreme python and development focused, and then slash commands
How do I get the username + discriminator / tag, only by the id?
!d discord.Client.fetch_user
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.
I tried
user = userID
ctx.send(f"{user.name}")
ty
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
I'm having a problem with disnake, member.status shows false status
Not recommended at all, use bot.get_user(id) or await bot.fetch_user(id)
although it's best to pair that with an attempt to get it from the cache with what @slate swan said
Is presence intent enabled?
Both in dev portal and in code
I figured you had only a user ID, but given what you're sending it should be cached 🙃
you can just use ```py
user = bot.get_user(id) or await bot.fetch_user(id)
._.
indeed
disnake already made a handy method
- what does it show vs what do you think it should show?
- what's your commands.Bot instantiation look like?
!d disnake.Client.get_or_fetch_user
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.
!d disnake.Client.getch_user
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.
is same
ye
getch_user?
🏃♂️ ty for saving me from hitting the _ 4 times
Funny name
get+catch user?
getch--get or fetch
clever
yes they are on
is that a slash command?
context menu
ow , does it always show that the user is offline?
it shows the offline status when I test it on my online friend
yes
fetch_member again
precenses intent?
hm?
yes, you need an intent to view if members are online
the Default one is enabled
not the default ones
disnake.Intents.default()
its a privelaged intent
Whether guild presence related events are enabled.
This corresponds to the following events:
This also corresponds to the following attributes and classes in terms of cache...
its not documented
ah
I never saw it 💀
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.
thanks
Why does it not output the guild id?
Hey
because you never ran the function 🧠
description=f"<a  Changed roles for {member.name}, +{ctx.role.name}")
Can you tell me what's the problem here
<a:thumb:id>
U meant a:
wdym
you never ran the function guild_id silly
Oh... lmao
description=f"Changed roles for {member.name}, +{ctx.role.name}"
Can you tell me what's the problem here
It doesn't send embed
a ) at the end isn't needed
unless it's in an embed and you're not showing everything ofc
description=f"Changed roles for {member.name}, +{ctx.role.name}"
Can you tell me what's the problem here
how can i fix dis
I mean there is some problem
Under Curly brackets
you didn't pass an argument to that function, silly
just show the whole command
wdym
you have to know what an argument is by now
#**__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"<a853182969618366464> 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
you should have errors in the console for sure if it isn't sending anything
After the "+"
How do I fix this error...?
Stop calling everyone silly, silly
how do i make the bot find out that the message author is itself?
if message.author == bot.user
!d discord.Client.user
property user: Optional[discord.user.ClientUser]```
Represents the connected client. `None` if not logged in.
Wrong Server My Man
The API doesn't return a field id.
You probably want data["guild"]["id"]
is it possible to detect if a user is currently muted in a vc
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
}
}
!d discord.VoiceState.self_mute
Indicates if the user is currently muted by their own accord.
Indicates if the user is currently muted by the guild.
ok thanks
And to get the VoiceState object it's simply the voice attribute on a discord.Member object.
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}!")```
And how do i check all the time if hes muted?
You don't need to check all the time
do i need to make a @client.event?
!d discord.on_voice_state_update
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...
message.content.lower()
That's some very basic Python :p
yeah im just new
Then you should consider learning more, as this is one of the first things you will learn.
!resources Can help
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
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?
so it would be: if discord.VoiceState.self_mute == True: ?
^
One bot with multiple tasks -> https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
So i want to check if a user is muted how do i do that
yeah but let's say I have 5 tasks, each one with 1s loop
they won't interrupt each other?
That's why asynchronous programming exists :p
ok cool, thnx 🙂
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
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
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...
yes
Then don't use ctx but those.
but then its an error with voice_state = ctx.author.voice
async def on_voice_state_update(member, before, after):
voice_state = member.author.voice
if voice_state.self_mute:
print("true")```
like this??
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.
But the voice_state = membe.author.voice is not working
As I said, you don't need it. Because of this.
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.
I dont get it
It worked thank you
Now choose if you want to check the voice state before or after they changed it.
What do you mean by "Stopped working"
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
But your bot starts correctly?
yeah
May you share more code? Issue is probably somewhere else.
on_message event . do you have one?
How can i get a voice channel by its id?
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)```
||
Use get_channel
You have an on_message event that broke all your commands, to fix it you simply need to add the following line at the end of that event:
await client.process_commands(message)
now it works
Glad to hear that 
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
print(member)```its just printing one member
!intents
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.
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()
!pypi neuralintents
thanks
That's probably not the message of the bot, but a user.
but if i delete message 2 times , it should delete its own message ri8?
No
why
!e
x = 1
print(x)
print(x)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 1
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
is there a way to see who deleted a msg if it was themselfs or a mod?
you can also do py x = await message.channel.send("...", delete_after=20) deletes message after 20sec
What's the object i need to make a bot add reactions?
Depends how you want to manipulate the message later.
@slate swani was thinking in the event on_message_delete
A message object
Error says all
You are giving a function instead of a snowflake as value.
just notices
i tried something like message.add_reaction("emoji") but i dont think it works
await
i used await too
how do you get a bot to send imported python files into a channel ?
And what was emoji
👍
:something:?
:thumbsup:
You need to use a raw emoji, such as \👍
i tried the raw emote p sure
Add a \ before sending it and copy paste that.
oh
I don't think it's possible to get all imported files/modules programmatically.
dame I was looking to use this to crate a discord game bot. do you have any suggestion on how to do it properly?
What are you trying to do?
Why would you need to send all imported files in a channel for that?
>>> 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)>}
?
@slate swan I have two files the game itself and the bot and i wanted to combine them using that function
Python 
doesn't seem to work either. it sends the message but doesn't add reactions.
What is your code now?
full or just the @client.command of the poll feature?
Where you add the reaction of course ^^
No \
When you send in chat use that, then copy paste what got sent.
\👍
This needs to be copy pasted.
do i need to place <> around the emote?
No
Only this
there's apparently something wrong in if message.author == client.user:
Such as?
AttributeError: 'str' object has no attribute 'author'
Why did you replaced the message variable to a string?
