#discord-bots
1 messages ยท Page 1041 of 1
which ide
VS code
๐
I made many more things in Python now ๐
like?
I learned how to add HTML, CSS, JS, TS, and Python together using Django
Then a flask API
did u learned css ;-;
Ah... chat is active, best time to leave ๐ถโโ๏ธ
Yea
hard for me
It is
I ignore that fact that I typed 15k lines of CSS
for the user interface and the administration panel
tf
css gives more brain damage than #esoteric-python
Thank you! So to clarify in this case, each event would be defined in separate cogs right? For example I just wrote this up for this:
class TestMessage(commands.Cog): # declaring the cog
def __init__(self, bot):
self.client = bot
@commands.Cog.listener()
async def on_message(self, message): #probably shouldnt use 'on_message' in a cog huh?
if message.content.lower().startswith('hi'):
await message.channel.send('hello')
def setup(bot):
bot.add_cog(TestMessage(bot))
If im understanding correctly, I create a cog for each message cog listener, then just load all of them in the main file and the conditions defined within each separate cog would determine whether it gets executed, yeah?
How is rust
speaking of rubber ducks I think I just rubber ducked myself in writing that out
Painful
I prefer to keep them inside a file called "listeners"
You should name your bot variable bot rather than client
Maybe
got it, is there any specific reason for that or is it just a general best practice?
indeed yes
Good naming practice
Since you're using bot
you ever ask a question and then the answer is so obvious it hurts your soul?
Yes
ye
same, thanks for the help

So one big listener file with seperate classes per the listener or just a bunch of listener events defined in the same class?
How would i make it so only the author of the cmd can press the button
3 css files its fine
what the

frick
yikes
yeah, that should work!
its working! now just trying to figure out best practice so I dont end up shooting myself in the foot as hard as I did last time
You should look at my JS files
i seen something weird when i was scrolling
using self.bot=bot is more preferable than self.client = bot ( variable naming ) everything else seems good here
7.6k lines of CSS
RIP
?
I do too now
Override the interaction_check method inside the view (other people can still click the button but won't respond if done correctly!)```py
async def interaction_check(self, interaction: Interaction) -> bool:
return True if ... else False # ... = would be something like interaction.user.id == 704839281838915675
I also hate JS
lmaoo
yep already changed, that was from copying code from another project I was working on and not noticing ๐ฌ
cool then :D
ok ill try thx
!pip javascript ๐ณ
PyScript is cool but I definitely don't see its relevance
One of the reasons why
Sorry guys last question, so if I name a bunch of listeners in one cog file for listeners (including multiple message listeners), would they ideally be separated into different classes?
Try 9 more files like that
wow code in 1 line
So?
im ded
Still debugging it
Do you not have source maps?
I coded it from scratch
with the second way I sent, you can have multiple listeners in same cog class
You wrote minified JS?
I'm no javascript developer but isn't jQuery bad?
100 lvl above #esoteric-python
Im gonna give it a shot, thanks
Not for this project
Yea
It powers a lot of JS scripts on the web so it shouldn't be that bad
I'm so confused
appreciate your folks' help. Its humbling as a senior data monkey to have no idea what im doing again
...?
Ok
No
how would i make the
interaction.user.id == 704839281838915675
part check if its the author of the message
ephemeral
ye
then u pass the id
how do i make the id the command author's id
cuz it cant be ctx.author.id or anything
ctx wouldnt be defined since its not a command
can u show ur code ill add
you can pass the context to your view class and check that
yes
class Game(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(label=' ',style=discord.ButtonStyle.grey, row=0, disabled=True)
async def Nothing1(self, interaction: discord.Interaction, button: discord.ui.Button):
self.value = True
@discord.ui.button(label='Up', style=discord.ButtonStyle.green, row=0)
async def Up(self, interaction: discord.Interaction, button: discord.ui.Button):
#await interaction.response.send_message('Confirming', ephemeral=True)
moveUp()
embedVar=getNormalEmbededData(title="Pick Apple Game", description="{}".format(getGameGrid()))
embedVar.add_field(name="Your Score", value=points, inline=True)
await interaction.response.edit_message(embed=embedVar)
self.value = True
@client.command()
async def game(ctx: commands.Context):
reset()
"""Asks the user a question to confirm something."""
# We create the view and assign it to a variable so we can wait for it later.
view = Game()
msg = await ctx.reply('Lets play a game', view=view)
# Wait for the View to stop listening for input...
await view.wait()
if view.value is None:
print('Timed out...')
elif view.value:
return
else:
print('Cancelled...')```
there is some
alr
class MyView(ui.View):
def __init__(self, context: commands.Context):
self.command_ctx = context
super().__init__()
async def interaction_check(self, inter):
if inter.user.id == self.command_ctx.author.id: # stuff```
yes
like that
for initialising the view you would have to pass a context in it
discord code blocks are trash when high width
select = Select(options = [
disnake.SelectOption[
label ="Help Base 2",emoji="",description ="Shows Second Help Embed",
],```
๐ฟ no, use pep8 to not exceed word limits per line
how is this invalid syntax
never closed the brackets
SelectOption(...)
wrong brackets.
[ [ ] error
all the brackets are messed up
also why that comma
ok
its fine to have an extra comma, also they may have more code below which they didnt send..
black formats stuff like that
..
no error in console
which you then read it lol
hover on the red line
,
invalid syntax
yes
how?

what should i do
close )
its closed after the line which is not in the image
ok
๐ man ignored me like i dont even exist, anyways, youre using wrong brackets
bruh
it should be ( instead of [ for the SelectMenu
use views
best
thx for the help guys!
:D
i wont ignore you๐ฅฐ
๐ cause u a qt
๐ฅฐ โค๏ธ
sorry bro
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
๐
ok trying this out now, are there different ways for the bot to reference itself when using cogs?
from discord.ext import commands
class TestMessage(commands.Cog): # declaring the cog
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, msg):
if msg.content.lower().startswith('hi'):
await msg.channel.send('hello')
@commands.Cog.listener()
async def self_message(self, msg):
if msg.author == bot.user: #Linter warning = "undefined name 'bot'"
await msg.add_reaction("๐")
def setup(bot):
bot.add_cog(TestMessage(bot))
message.author == bot.user doesnt seem to work like it does outside without cogs since I use this same syntax in multiple other live bots.
self.bot
you need to enter the event name inside the @torpid palmtener
well self.bot is your bot instance so use it lol
ping lol
oh god
lis got pinged
lol
good for them ig ๐ ?
inside lis
tener
ye
interesting
Im on a roll with bad questions tonight. I keep expecting my issues to be due to some new parts of the library that I havent handled but theyre consistently just me making dumb mistakes and thinking its something new
๐ณ cannot disagree
thanks for the help
its fine and we are here to help with any issues you face
atleast you understand what you are doing :p
debatable but I appreciate the sentiment lol.
sarthak is such a lovely, kind person๐ฅฐ
I agree ๐ญ
sparky want a compliment 
๐
yes?
sparky is a nice cool person๐ฅฐ
!ot ๐
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
SIKE
kali-ma-linux
xD
i give my love and you reject it smh๐ก
can you both stop? or take this to an ot channel for real
ok
thanks <3 u too
๐ง > ๐ช
lol
๐ณ
okimii's the best at making weirded reactions
now stop

๐ฟ i have an exam in 50 minutes so guess i'll take a leave, cya guys
baiiii goodluck
robinnnn
B.O.L
hi
robin i see youuu๐๏ธ ๐๏ธ
i observe this chat
robin wants a compliment๐
no i was actually about to tell you all to get back on topic
but only sarthak can give it so bye bye
so consider that said
robin mad he got no compliment anyway back on topic
yes please
.topic
Suggest more topics here!
boring .........24
Is having basic things like not changing presence on_ready and not calling commands.Bot client considered a feature?
๐
thats more of a good practices
for the backend, we could say that.
go study for exam
but doesn't seem like many follow it unfortunately
bad yt tutorials.
im not a "study at last moment" person, and lets not make it off topic again
..
revise*
better error handling i guess, i have seen bots which dont even respond with what problem was there with the invocation of the commands
so I have been getting some images through an api but they are super low quality.. any python lib uk of which upscales the resolution and doesnt take time?
buttons so they can leave behind reactions and their 2/1s iirc ratelimit
toatally me
i dont have error handlers
you cannot increase the quality of an image you already have~
is it 2/1s or 1/1s?
u can through machine learning models
read this ^
thats yet another thing, and it fails the "doesnt take time" part.
ye thats why I came here
otherwise I already know about opencv lib etc..
ig its not yet possible for both the options (less time and upscaling) hmm
thx for the help
opencv is a resource-eating library, even if you wanted to use those kind of features, you'd have to create a seperate api to not let your bot crash every often or so
right
wish discord allowed us to customize image sizes :c
atleast I would have picked a fixed size for thumbnail so it didnt look very small on phone
wdym? you could compress images by yourself?
resize*
no like set_thumbnail images really small on phone
even if its a good resolution discord wont increase its size
well, thats how it is, and it is what it is
I mean thats why I said "wish"
@spring verge use an image api
so I get why I needed self.bot, that was me being mad dumb, but Im not sure what you mean here? Reaction isnt working so I know im doing something very wrong.
U shouldn't also become a chat at the last moment person
hmm looking for one which allows good amount of requests for free version .. well thats my fault for not having money ig
thx for the suggestion
your second listener won't get triggered as there's no event named "cog_message" event
so it should also just be normal on_message
you need to pass "on_message" in the @listener decorator for that to work
@commands.Cog.listener("on_message")
async def cog_message(....
oh... quotes....
๐ agreed, imma leave now
๐
oh so this keeps it from redefining the same event
you can have seperate functions for the same events to keep your code organized if you like
@commands.Cog.listener("on_message")
async def message_one(...): ...
@commands.Cog.listener("on_message")
async def message_two(...): ...
both of them will get triggered when a message is sent
just tried this and now both arent executed ๐ฎ
from discord.ext import commands
class TestMessage(commands.Cog): # declaring the cog
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener("on_message")
async def user_message(self, msg):
if msg.content.lower().startswith('hi'):
await msg.channel.send('hello')
@commands.Cog.listener("on_message")
async def meta_message(self, msg):
emoji = '\N{THUMBS UP SIGN}'
if msg.author == self.bot:
await msg.add_reaction(emoji)
def setup(bot):
bot.add_cog(TestMessage(bot)
weird
ok so that was my bad, now its just the second. Maybe Im just doing emoji referencing wrong
just the second not working*
its something to do with if msg.author == self.bot:
self.bot.user
re-posting the final message from #965291445999239258:
alrighty, that's a wrap! ๐๐ป
this thread will be closed
the proposal for a library discussion thread was made, but i didn't see too much interest or desire for the idea, so we'll leave it at 2 threads for now (#965291480992321536 and #965291516031549500)
if you strongly disagree, or have any future ideas for a thread, come and make your case in #community-meta!
ok
cant i run another command like
async def button_callback(interaction):
ck(ctx)
u can bro
coroutine 'Command.call' was never awaited
ck(ctx)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
172.18.0.1 - - [13/May/2022 04:00:36] "GET / HTTP/1.1" 200 -
getting this error@nimble plume
fgl
await ck(ctx)
ok ok
also dont use replit
You are calling a command?
late bro
Wtf for
help
With
Calling a command is not a good idea just saying
why
Command is supposed to be a command and not a callable
im guessing thats not a command
The code that should be executed may be brought out to the separated module
It is
Command.__call__
Basically invoking a command
interaction != ctx
They share attributes but are not the same
Yk
So as I said, bring the code that should be executed from several places to one module and import it from there
yes
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 825, in getaddrinfo
return await self.run_in_executor(
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/socket.py", line 918, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
172.18.0.1 - - [13/May/2022 04:22:30] "HEAD / HTTP/1.1" 200 -
pls tell me an easy solution to call it









What address you're trying to make request to? Seems like the hostname isn't correct




import discord
import os
from discord.ext import commands
TOKEN = 'token'
bot = commands.Bot(command_prefix='!!')
client = discord.Client()
print('Running........')
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
# some codes
bot.run('token')
bot is online
but commands dont work and it doesn print we have logged in as....
can anyone help?
@last cedar Remove client, use bot instead
import discord
import os
from discord.ext import commands
TOKEN = 'token'
bot = commands.Bot(command_prefix='!!')
print('Running........')
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
# some codes
bot.run('token')
dude thank you so much it worked
i was about to switch to discord.js
Useless TOKEN variable
@client.event
async def on_message_delete(message):
snipe_message_author[message.channel.id] = message.author
snipe_message_content[message.channel.id] = message.content
await sleep(60)
del snipe_message_author[message.channel.id]
del snipe_message_content[message.channel.id]
``` correct?
It's
time.sleep()
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [Whatโs New in 3.10โs Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
Use this so it won't freeze your bot
await asyncio.sleep(60) this is correct?
Yes
thx
hmm
Kiff connected!
Ignoring exception in command hello:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.```
=/
you didnt provide a required arg while invoking the cmd
for example
@Command
async def cmd(ctx, member): ...
#when *running* the command on discord
<prefix>cmd <member>
# if you dont provide the member argument, it'll raise that error
oh, sorry
thx
!d discord.Streaming
class discord.Streaming(*, name, url, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.Activity") that represents a Discord streaming status.
This is typically displayed via **Streaming** on the official Discord client...
successfully moved 800 lines of code to cogs (first time using) and everything is finally working and so much cleaner
anyone know if its possible to have a pin-message button?
change_presence(type=discord.ActivityType.streaming, ...)
Or that, yea
change_presence(activity=discord.Streaming(...))
so when messages are cleared by my bot, i want it to say py "I have cleared",amount,"messages for you" but i get this error await ctx.channel.send("I have deleted",amount,"messages for you.") TypeError: Messageable.send() takes from 1 to 2 positional arguments but 4 were given
how to fix this
use an f-string or other forms of string interpolation
!e
amount = 10
print(f"I have cleared {amount} messages for you")
@elfin island :white_check_mark: Your eval job has completed with return code 0.
I have cleared 10 messages for you
k
thx
so i want a joke command my code is
import os
import requests
from dotenv import load_dotenv
import random
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
client = commands.Bot(command_prefix = "Pyramid: ")
def get_joke():
r = requests.get("https://v2.jokeapi.dev/joke/Miscellaneous,Dark,Spooky?blacklistFlags=racist&type=twopart")
json_data = r.json()
if json_data["type"] == "single":
return json_data["joke"]
elif json_data["type"] == "twopart":
return "\n".join([json_data[x] for x in ["setup","delivery"]])
else:
return f"Sorry, I dont know how to tell a joke of type {json_data['type']}"
@client.event
async def on_ready():
print("Bot is ready")
@client.command()
async def Joke(ctx,joke):
joke = get_joke()
ctx.channel.send(joke)
load_dotenv()
client.run(os.getenv('TOKEN'))
i get this transformed = await self.transform(ctx, param) File "C:\Users\n/a\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ext\commands\core.py", line 599, in transform raise MissingRequiredArgument(param) nextcord.ext.commands.errors.MissingRequiredArgument: joke is a required argument that is missing.
joke is not an argument that the command caster would send, remove it from the args
how
๎บง python3 main.py
Traceback (most recent call last):
File "main.py", line 14, in <module>
import clean_code
ModuleNotFoundError: No module named 'clean_code'
anyone?
k
How many slash commands can a single bot have?
there is no module named clean_code 
there is not a limit i think
!import clean_code
Star / Wildcard imports
Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.
Example:
>>> from math import *
>>> sin(pi / 2)
1.0
This is discouraged, for various reasons:
Example:
>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2) # uses sin from math rather than your custom sin
โข Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
โข Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
โข Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.
How should you import?
โข Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)
>>> import math
>>> math.sin(math.pi / 2)
โข Explicitly import certain names from the module
>>> from math import sin, pi
>>> sin(pi / 2)
Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]
[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python
how do i send the joke then, just not make it a argument?
you have to remove joke from the argument of the command function and stop
you will get your joke from your api
!e
def foo():
return "ok"
def uwu():
message = foo()
print(message)
def bar(message):
message = foo()
print(message)
!e
def foo():
return "ok"
def uwu():
message = foo()
print(message)
perform uwu?
!e
def foo():
return "ok"
def uwu():
message = foo()
print(message)
def bar(message):
message = foo()
print(message)
uwu()
bar()
@placid skiff :x: Your eval job has completed with return code 1.
001 | ok
002 | Traceback (most recent call last):
003 | File "<string>", line 13, in <module>
004 | TypeError: bar() missing 1 required positional argument: 'message'
as you see it gets the error on bar because it takes message as argument but i give no message in input of the function
help
ctx.channel.send(joke)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
joke is not argument
Await the send.
This worked a month ago, but now it doesn't. Where did I go wrong?
@bot.command(name = "announce")
@commands.has_role("bot bot")
async def announce(ctx, role: discord.Role, *, message):
channel = bot.get_channel(something something)
embed = discord.Embed(
title = f"Announcement",
description = f"Announcement for {role.mention},\n\n{message}",
color = 0xFFFF00,
timestamp = datetime.utcnow())
embed.set_footer(text = f"{ctx.message.author.user.name}")
await ctx.message.delete()
await channel.send(embed = embed)
@announce.error
async def announce_error(ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.message.delete()
await ctx.send("You don't have permission to use this command!", delete_after = 3)
how? message.send worked in other commands
Yeah prob because you awaited those.
error?~
No error, just no action
add else: raise error at the end of your error handler
It says AttributeError: "Member" object has no attribute "user"
how to await it then code:
def get_joke():
r = requests.get("https://v2.jokeapi.dev/joke/Miscellaneous,Dark,Spooky?blacklistFlags=racist&type=twopart")
json_data = r.json()
if json_data["type"] == "single":
return json_data["joke"]
elif json_data["type"] == "twopart":
return "\n".join([json_data[x] for x in ["setup","delivery"]])
else:
return f"Sorry, I dont know how to tell a joke of type {json_data['type']}"
@client.command()
async def Joke(ctx):
joke = get_joke()
ctx.channel.send(joke)
embed.set_footer(text = f"{ctx.message.author.user.name}") is wrong
should be ctx.author.name
Eh?
Aight, lemme change that
@slate swan it works, man! Thanks!
But I wonder why this code works back then
But now it doesn't
Await the last line
!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.
ctx.send is just a shorthand for ctx.channel.send, it has been shortened because if you do .send on the context you can only really have one destination. That being the response.
i want to make membercount command and after surfing on internet i found this
@bot.command(name='membercount')
async def membercount(ctx):
await ctx.send(ctx.guild.member_count)
like how does this work
there is no if messag ==
What part exactly?
like how does the script recognize the command
Oh, well this uses the Bot extension that is integrated into d.py.
for example $membercount
How to make discord.Role case insensitive?
Like announce testrole message but the mentioned role is Testrole
@bot.command(name = "announce")
@commands.has_role("bot bot")
async def announce(ctx, role: discord.Role, *, message):
channel = bot.get_channel(something something)
embed = discord.Embed(
title = f"Announcement",
description = f"Announcement for {role.mention},\n\n{message}",
color = 0xFFFF00,
timestamp = datetime.utcnow())
embed.set_footer(text = f"{ctx.message.author.name}")
await ctx.message.delete()
await channel.send(embed = embed)
@announce.error
async def announce_error(ctx, error):
if isinstance(error, commands.MissingRole):
await ctx.message.delete()
await ctx.send("You don't have permission to use this command!", delete_after = 3)โ
else:
raise error
to which command does this script react to?
to membercount?
Yeah prefix then the command name.
so when someone writes: membercount in chat this script runs?
Well with the prefix ofcourse.
oh ok ty
That's automatically added.
There isn't really a good way for that, you could make a check inside the command tough.
you can't, you will have to create a custom check and do it inside your custom check
Better to change the role, right?
It's best to just not have role as an argument.
not totally, I always create custom checks for roles so i can extract the role from database so my bot would have dynamic role checks
The role is a must for this announcement, there are 5 groups in the server
@client.command()
@has_permissions(kick_members=True)
async def Kick(ctx, member : discord.Member)```
how to add a reason for this
You can't mention inside an embed anyways
for example if I have roleplay bot with custom roles integration for every guild i want that some commands are accessible only for some roles, the builtin custom check isn't enough to check them dynamically so a custom check comes handy
It can tho
..., *, reason: str)
nope they will just look like this: <@id>
Yeah but they won't get pinged.
So no one will get a ping?
Yep it just appears as a normal mention without a ping.
So the ping should be outside of embed?
Yes.
Aight, thank you Panda and BlvckTvrsier
Could you show your code?
@bot.command(name='membercount')
async def membercount(ctx):
await ctx.send(ctx.guild.member_count)
do you have intents?
How did you define bot?
bot = commands.Bot(command_prefix='!!')
print('Running........')
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
@client.event
async def on_message(msg):
if msg.content == "<@bot_id>":
await msg.reply(conent = "hello",mention_author=False)
client.process_commands(msg)
``` this is correct?
Then you should type !!membercount
ooh
yes but it isn't the correct way to make a when_mentioned_or method
so what is correct method?
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example...
still didnt work
Did you got an error?
no
*content
?
import discord
import os
from discord.ext import commands
maybe the imports are wrong
do i need seperate package for ctx thing
!paste Could you show a bit more?
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ok hold on
Make sure to hide the token.
import discord
import os
from discord.ext import commands
TOKEN = 'DDDDDDDD'
bot = commands.Bot(command_prefix='$')
print('Running........')
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
@bot.event
async def on_message(message):
if message.author == bot.user:
return
@bot.command(name='membercount')
async def membercount(ctx):
await ctx.send(ctx.guild.member_count)
bot.run('NDDDD)
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Yep
i should add this?
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
I doubt it is an intents issue, instead, see this https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working
that too, but member_count wont work without the intents anyways
Oh, for that, yeah, but for why the command didn't get invoked, the link above
agreed
getting channel by id through discord.utils?
Donโt
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
using client.get
No
Use the get_channel method
It gets the channel from the cache
i wanted to put the id through db
Which is faster then looping through all of the channels and checking itโs id attribute
You can
Just get the channel by the get_channel method
cursor.execute(f"SELECT channel_id FROM logs WHERE guild_id = {ctx.guild.id}")
chan = cursor.fetchone()```
channel = self.client.get_channel(id=chan[0])
await channel.send(embed=embed)```
this won't work?
bruh you have the guild 
^
?
Oh wait we both wrong
you have the guild object, use the method Coke suggested
Bruh he will get the channel after that statement...
Also id is a positional only argument
so? i have setuped it already
o
use ctx.guild.get_channel(id)
channel = ctx.guild.get_channel(chan[0])
await channel.send(embed=embed)```
Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
i get this error
@placid skiff?
Probably not in the cache
Try fetching it
what
sql ?
No
then
!d discord.Guild.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") or [`Thread`](https://discordpy.readthedocs.io/en/master/api.html#discord.Thread "discord.Thread") with the specified ID...
thank you
Can i run two separate bots using
bot.run("TOKEN1")
bot.run("TOKEN2")
```?
this code works but for some reason the person i unbanned does not show up in the server list is it a bug or problem in my code:
import discord
import os
import requests
from dotenv import load_dotenv
import random
from discord.ext import commands
from discord import Member
from discord.ext.commands import has_permissions, MissingPermissions
client = commands.Bot(command_prefix = "Pyramid: ")
@client.command()
@has_permissions(ban_members=True)
async def Unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"I have unbanned {user.mention}")
load_dotenv()
client.run(os.getenv('TOKEN'))
is it cause bot names are identical
The member/bot you've unbanned won't join automatically, you need to invite it again
don't use lucas' unban code ๐ฉ
No, bot.run() blocks your code, so it will execute the first bot.run() but not the second one.
TypeError: Expected discord.Colour, int, or Embed.Empty but received method instead.
This error comes when I try to assign a colour to an embed like this
embed = discord.Embed(colour=discord.Colour.green)
help wen
!d discord.Colour
class discord.Colour(value)```
Represents a Discord role colour. This class is similar
to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)").
There is an alias for this called Color...
u need to call it
mann just tell me why this error comes and how to fucking fix it
so green()
:hehe_hehe:
Do you understand why?
yes
i didnt call it so it accepted it as a method
not a func

Okay! Just wanted to know whether I should've explained it

Hey, for some reason the on_member_join event isn't activating when a user joins. I have intents.members enabled.
code
which part do you need
the on_member_join event
@commands.Cog.listener()
async def on_member_join(self, member):
print('member joined')
it's in a cog
Was the cog loaded?
lemme check
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
for some reason no
Then load it using the Bot.load_extension method
i didn't put it in the cog folder lol
tysm it worked <3
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\mod.py", line 206, in mute_command
unmutes = await self.mute_members(ctx.message, targets, hours, reason)
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\cogs\mod.py", line 166, in mute_members
if not self.mute_role in target.roles:
AttributeError: 'Mod' object has no attribute 'mute_role'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\Bot2.py", line 28, in on_command_error
raise error
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Mod' object has no attribute 'mute_role'```
Someone plz
have you read the error?
Yes does that mean it hasnt specified the role to give the user
not True
what's the error, tell me
What happens if i dont?
then you'll keep the error and just ctrl+a + Del
The role is not the highest in the chain in the server
and where do you think you can read that in the error?
hold on a minute
Is that actually right?
tho
Can We Len Imports and Lines That Is In Bot
how do i add the intents
Traceback (most recent call last):
File "main.py", line 5, in <module>
bot=commands.Bot(command_prefix="!")
TypeError: init() missing 1 required keyword-only argument: 'intents'
Read https://www.w3schools.com/python/gloss_python_function_keyword_arguments.asp, the value should be Intents.all() or Intents.default()
ok
thanks
where do i add it in
after command_prefix?
intens=Intents.all()?
something like that
Error points you to a specific line:
bot=commands.Bot(command_prefix="!")
intents = discord.Intents.all()
bot=commands.Bot(command_prefix="!", intents=intents)```
bot = commands.Bot(
command_prefix="!",
intents=Intents.default(),
)
If you use keyworded arguments order shouldn't matter by the way
ok
f(a=a, b=b)
Is the same as
f(b=b, a=a)
Yep but for understanding we do it so
ok
Correct
guys i'm using with open to create a file and the name of the file is a variable as well and i want it to be created as txt so how ?
alt f4

the order wouldn't really matter its a kwarg so it would be called by its name and not position
You make a new file and put .txt as the file extension
you would just open it and write to it and ofc you add the file extension
yeah i mistaked i added variable.txt but variable + ".txt" was the right one
how to make a command of 2 words?
ah lol
prefix command argument
like this ig
group commands lol
make purge an argument?
why does it not actually unban someone
(noone except for me and the bot is there)
my code is:
@client.command()
@has_permissions(ban_members=True)
async def Ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.channel.send(f"I have banned {member}")
@client.command()
@has_permissions(ban_members=True)
async def Unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f"I have unbanned {user.mention}")
load_dotenv()
client.run(os.getenv('TOKEN'))
@bot.command()
async def restock(ctx, category, stuff):
attachment_url = ctx.message.attachments[0].url
stuff = requests.get(attachment_url)
print(stuff.content)
with open(category + ".txt", "r+") as file:
file.write(stuff + '\n')
await ctx.send("added successfully!")```
discord.ext.commands.errors.MissingRequiredArgument: stuff is a required argument that is missing.
how can i make it count the file i requested from the message as a argument ?
help this code does not unban the user
are u really sure the bot has perms to do anyways?
it has admin perms
are you unbanning a bot?
100% got that from Lucas
you wont be able to do that iirc
hii
i see as well
Hola
that mr barney helped me in #help-coconut
he inspired me to do shit in past but i honestly don't bother copying shit for no purpose
=.=
You shouldnโt try to unban people by name+discriminator. Thatโs an inherent security flaw.
then how do u learn
what.....should i do?
just telling u
yeah i do learn from him and others and websites/etc how stuff work/syntax etc but i don't like to copy the exact same code i need and paste it
then how
then try to modify it ig?
instead of copy paste like a robot
how to make time by type s, h?
Just by id
s-second, h=hour
well yeah that's what i do most of the time if i face any issues
user.id? or what i;ve never used id
- i understand what the code does and how it works so i can use it for other uses in future
too plain, what do you exactly want?
WHAT???
I mean thatโs the most precise and unique part of user identification
maybe he wants to make timer instead of time
So when it comes down to moderation Iโd consider using that.
same
u can change anything except id
not to write slowmode 3600, write slowmode 1h
he wants the s, m, h, d thing
you'll have to stuff like getting the digit out of the input
i forgot what is it call
yea
sarth told me before
cuz i literally created a second -> h, m, s function
so he shows me
this one
found it
@slate swan
!d datetime.timedelta
!d datetime.timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
@slate swan
thx
np
thank sarth ๐คฃ
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
seccd = round(error.cooldown.get_retry_after())
mincd = 0
hrcd = 0
rseccd = 0
rmincd = 0
if seccd > 59:
rseccd = int(seccd % 60)
mincd = int((seccd - rseccd) / 60)
if mincd > 59:
rmincd = int(mincd % 60)
hrcd = int((mincd - rmincd) / 60)
else:
rseccd = seccd
await ctx.send(f'''
Dont spam :/
Try again in another **{hrcd}h {rmincd}m {rseccd}s**
''')
I mean ๐ why are you so free
this better?
@client.command()
@has_permissions(ban_members=True)
async def Unban(ctx, id: discord.Member.id):
banned_members = ctx.guild.bans()
for ban_entry in banned_members:
user = ban_entry.user
if user.id == id:
await ctx.send(f"I have unbanned {user}")
i just read the api and tried this
there might be mistake
and also i forgot
lucas?
await ctx.guild.unban(user)
just wait for an int and get the user
oh
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to
do this.
There's no need
await unban(Object(id=1234567))
Is fine.
!e ```py
from time import strftime, gmtime
print(strftime("Try again in another %Hh %Mm %Ss", gmtime(6662398)))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
Try again in another **02h 39m 58s**

how to call a async function with button callback with same context
and it can still be done with
await ctx.guild.unban((bot.get_user(int))
pylint getting a stroke rn
๐คซ
Won't work
Hence the stroke
Since it's gonna return None and the error is gonna be NoneType has no attribute id
everybody ignoring me
what
how to get a user status
what happened my frand
I have no clue as what you mean.
is this better ```py
@client.command()
@has_permissions(ban_members=True)
async def Unban(ctx, id):
user = client.get_user(id=id)
await discord.Guild.unban(user=user)
Don't literally use the class.
you would need to typehint id as an int and the unban coro needs to be an instance of the class Guild
and you should use or if the user isnt in cache and it returns none
@gaunt ice how do i call a async function with button callback with same context

@cloud dawn
ok
hmm
np
what do u want to make
so like ```py
id : int
?
how do i do this
wait do i use
ctx.guild.bans()
i have a command utility to configure a guild and i made a new command with buttons where i want to add every command function like that
duck = bot.get_user(69420) or await bot.fetch_user(69420)
Also id is a positional only argument
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.ext.commands.Bot.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...
.
what
Solved
@bot.command()
async def restock(ctx, category):
attachment_url = ctx.message.attachments[0].url
swallo = requests.get(attachment_url)
poggywoggy = str(swallo.content)
print(poggywoggy)
with open(category + ".txt", "r+") as file:
file.write(poggywoggy + '\n')
await ctx.send("added successfully!")```
how do i use cogs
how to get the server region ?
why what's wrong with it exactly?
iirc only voice channels got regions
!d discord.Guild.region
No documentation found for the requested symbol.
but why
anyways here's the docs link https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.region

removed in 2.0
is it not updated in the docs?
oh i'm looking at the stable docs nevermind
requests is blocking, probably shouldn't use it as dpy is an async lib
!d aiohttp consider this instead
ohk
SO COGS HOW DO I START
??
!d discord.ext.commands.bot.load_extension
No documentation found for the requested symbol.
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or
listeners...
the class has to inherit from commands.Cog
and the file has to have a setup function
then in main.py
cogs = [โcog_file_nameโ, โcog_file_name2โ]
what happens if i wanna annotate my arg to be a converter, but in the Converter i have some args i need to pass
for cog in cogs:
bot.load_extension(cog)
what is giveaway_answers
@slate swan
what on earth is
try:
pass
lmao
use an error handler
@giveaway.error
async def on_giveaway_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
do this
also for the error
you arnt doing line 713 right
Local handlers are cringe
;/
Especially for this error
true
Make global one
Try except ยฏ\_(ใ)_/ยฏ
How can i check if a member join?
MissingRequiredArgument can't be catched by it
Ye use global for that
!d discord.on_member_join
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
else:
raise error```
And your problems are solved
what about missing arguments
Global
No
It will raise literally everything if there's no situation
then if channel == None raise error
no
or something
What if multiple arguments
what about it
Sorry but this makes no sense
im on my phone gimme a break ;/
use a loop first
and how can i send a message in a specific chnnel?
bot.get_channel(id).send("hi")
thanks
On mobile
Typical global handler looks like this
@commands.Cog.listener("")
async def on_command_error(ctx, error):
if isinstance(error, commands.SomeError):
# do action
elif isinstance(error, commands.SomeOtherError):
# do another action
else:
raise error```
@bot.command()
async def avatar(ctx: commands.Context, member: disnake.Member = None):
if member == None:
member = ctx.author
await ctx.channel.send(member.avatar_url)
like this
or something
Very cool error handler message getter trust https://github.com/Exenifix/AIAS/blob/master/utils/errors.py#L122-L147
use
m = member or ctx.author
instead
oh ye
good idea
ah but it only works if member evals to false
if member is none then wont it still take it
U can default it anything but
hmm
!e
def no(a = False):
M = a or 1
print(M)
no()
!e
def no(a = False):
M = a or 1
print(M)
no()
@regal pulsar :white_check_mark: Your eval job has completed with return code 0.
1
I hate coding in mlbile
!e
def no(a = False):
M = a or 1
print(M)
no(9)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
9
yikes
Huh
trash app
not according to the pictures it isnt
Personally I donโt agree with learning that way but everyone learns differently so thereโs that
im joking ;-;
its explaining is so bad its like w3school
its awful
Use replit better
w3school isnt bad
even i wont go that far ๐จ
/j???
I don't have a constant resource I just google ๐
can anyone guess what project this is
Use vscode online if u dont want to run and goto replit if u want to run
Discord bot
Replit
but it has tkinter
This could benefit from separation of concerns
How did you even get tkinter to work alongside a discord bot? Threading?
isnt mine ๐ฉ
..
hmm
I hate typing
How do I install discord.py?
i hate talking to yo
go to command prompt
OK
type pip install discord
No
or is it pip install discord.py
Install from github
idr
is this it?
it is
alr
or you could just use disnake
I can barely see
pip install disnake
Why maximise cmd
I was wondering why install wasn't working... is this why you only put one L?
๐
im on ipad ;/
typo
oh
bruh
so it's pip install discord?
What's that?
a fork of discord.py
Why?
basically the same thing but more features
py -m pip install git+https://github.com/Rapptz/discord.py
alright
No?
disnake is a good alternative
Itโs bAck
It recently got back
Wait so what do I use?
I want discord.py not disnake
yes
d.py has less stuff though
I only came here to figure out what I was doing wrong
lower administator
Not for recommendations
pip install discord then
Spell administrator lowercase and correctly then yes
i already told you what to do then ;-;
administrator is just one-
lol
Thanks
np
On mobile can't type
huh?
Spelling
for member in ctx.guild:
await DMChannel.send(member, โVery friendly messageโ)
administrator
administrator
๐ฅฒ
its okay, just spell administrator right before coming back with an error again ๐ซ
huh
kidding
we don't work for free
lmao
Alr take ๐
we only take snail mail, fyi
Can u show the imports
imports please ;/
POV: it is py-cord
:/
RIP
๐จ
imagine using pycord for bot
What's up with py-cord not working w/ discord.ext.commands.Bot?
imagine not using discum
Imagined what now?
and yes its a thing
iirc its discord.Bot
Don't know why they'd do that
no its discord.ext.commands.Bot itself
hmm ill help
but
can you meow for me
New mentions in gamedevelopment
pycord supports both commands.Bot and disocrd.Bot the second one is nonsense though
:)
Lol only know i discover that Py-script was announced
@slate swan uninstall pycord and install it again
๐ซฅ
im using a command to add seperated line text to a specific file but it adds with spaces how can i not allow it doing this ?
they changed it back
writelines?
no
i'll do now and try
show how you write in thr file
How do you write those
it was pycord
@bot.command()
async def restock(ctx, category):
attachment_url = ctx.message.attachments[0].url
swallo = requests.get(attachment_url)
poggywoggy = (swallo.content)
b = poggywoggy.decode("utf-8")
print(b)
with open(category + ".txt", "a") as file:
file.write(b+'\n')
await ctx.send("added successfully!")```
Back
with open(โfile.txtโ, mode=โwโ, encoding=โutf8โ) as file:
for line in lines:
file.writelines(line)
thought so, thanks for the confirmation uwu sarthak, and how did your test go? ๐
i tried writelines just now and it'll not work
Why mode =
yw, it was English so... pretty decent
idk
You need to specify mode don't you?
you dont
What's the default?
read and write i think
easy, good though


huh?