#discord-bots
1 messages · Page 809 of 1
they were talking about mentions being prefix
uhuh
it responds?
Can you send a screenshot of the code in the ide so i can see how its currently formated
exactly
meaning you can do @unkempt canyon help and it will respond
go to sleep bro😭
it's 12 pm my guy
isnt your bedtime 10?
So it can see message content if it's pinged...
12 pm is afternoon bro
hes high
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
Dw
@slate swan Can you help me?
Ok yeah he's definitely high
sure
its 2am and im doing a assignment due TODAY😔
I don't get the error
exactly, get off discord
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
lmao
or what
teacher schold
So what should i do?
scold
I dont know stuff
turns off
good
It looks like things are double indented?
wdym
There should be 1 line under each try: not 2. It looks like its double indented
so i didnt learn about indentation till now
👀
bro
i hope you're joking because you make no sense 😭😭
like bro what😭
..
I hate being on mobile because i cant give examples aaaaa
Im not gonna argue because it's 2 am for you and I understand how your brain works at 2 am

satisfied?
Try just indenting the bottom exception and see if it accepts it
Add, *
No
Without message intents, is the gateway event still dispatched but with a partial message object, or is it not dispatched at all like with how member intents and GUILD_MEMBER_ADD works?
not sure, but I'm guessing yeah
async def msg(ctx, user, discord.User,*,msg)```
you can check this link
🏃
Ok that article answered my question
you cant add a class as params?
I remember hearing about it but I forgot
it looks like it sends the event but without the message content etc
Yea
If your bot or app is not approved for message content, the following fields of the message object in Gateway and API payloads will be empty—either an empty string or empty array, depending on the data type—when you receive a message:
content
embeds
attachments
components
yeah since the intent isnt on why would it
Guess I need to fix my typehints now
LMAOOO
If I am wrong, I'll be very glad to be corrected
yeah
great
lucky
L
go sleep
Because I’m similar cases it outright doesn’t dispatch the event. Take presence intents, without it PRESENCE_UPDATE is NOT dispatched, you do not receive a partial presence object
this reply is a W
I refuse
ratio
ot
you cant even react😭
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
mhmmm
thats odd
Off I am at phone so I skip whole code lmao
😅
I am sry abt that
happens i sometimes forget define on mobile
🧑🦯
😅
@bot.command()
async def msg(context, user:discord.User,*,message)
await user.send(message) ```
capital await lol
Ik that
indents are off
and forgot a colon
Lmao mob problem

so you know each indentation level should be 4 spaces or a tab to follow pep8
Hmm
tab == 4 spaces
Ik or a tab space

each colon adds a indentation level btw
Hmm
u can "turn on indents" on discord?
Yah
or are u just talking about 4 spaces
okimii has been disconnected from the gateway
Lmao
ah ok
i know lol
we were talking about indents right?
but yes i do
i disabled it 🧠
its 75
why 100 then
the actual system kicks off at 75 though
when you get a message from the system it says 75 and if you check the length of the guilds your bot is in its 75
confusion
okay
my guess is maybe discord's idea is that when a bot hits 75 servers it would get the warning, and at 100 servers the messages would become blank
not only messages
since even the application process only becomes available on hitting the threshold (75 ig)
PRESENCE INTENT
Required for your bot to receive Presence Update events.
NOTE: Once your bot reaches 100 or more servers, this will require verification and approval. Read more here
SERVER MEMBERS INTENT
Required for your bot to receive events listed under GUILD_MEMBERS.
NOTE: Once your bot reaches 100 or more servers, this will require verification and approval. Read more here
MESSAGE CONTENT INTENT
This intent will not be enforced until after April 30, 2022. Read more here.
Will be required for your bot to receive message content in most messages.
NOTE: After April 30, 2022, once your bot reaches 100 or more servers, this will require verification and approval. Read more here
lol
jfl i just got my bot working too, i feel so silly now
but oh well at least i have the chance to do it right from the start
im not even gonna bother tbh, i dont like slash commands
bro.
how do you not like slash commands
idk
how do you not know
prefix is easier to understand than mentions, but slash commands seem really complex
they're a mess from a user's POV, imagine 15 bots in a server, all have all their commands as / commands
no?
idk i never used slash commands much myself
*imo
one of the reasons / commands are better is bots to overwrite each other and if you dont know a command or you dont know the prefix of the bot you should go straight to slash commands because its like a default prefix
but is it easy to make the same command many times though
just like any command
i guess its good actually
it just takes interaction and not Context and a new decorator
good for users, but complex for me
and other stuff you have to add
well not for me🏃
i like that i don't have to build my own UI to list all the stuff the bot can do
i mean i was trying to figure out how to make a lot of commands for my bot but in a way that users could navigate easily, and the slash commands does a really good job for that
discord bot development is so involved ngl
ig so
i mean its great it has all these things though
Hello Everyone!! Help needed here!!
#1: For how long is a button usable
#2: How can I make it usable after I have restarted the bot
1.forever until a reset or you stop listening to it
2.persistent views
thanks, whats persistent views
!d discord.Client.persistent_views
property persistent_views: Sequence[discord.ui.view.View]```
A sequence of persistent views added to the client.
New in version 2.0.
yeah
thanks will look into it 🙏
yw
am using disnake, it should be same right?
!d disnake.Client.persistent_views
property persistent_views: Sequence[disnake.ui.view.View]```
A sequence of persistent views added to the client.
New in version 2.0.
yes
thanks
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
yw
thanks
hi
hi dek
No thanks
bro
?
nice puppy
change your profile picture
Calm down
- Use AsyncIOScheduler (coz your bot is async.. right? And you need to run coros)
- apscheduler isn't an extension to discord related libraries, so you don't need to pass bot in init, instead do ```py
from apscheduler.schedulers.asyncio import AsyncIOScheduler
bot.scheduler = AsyncIOScheduler(event_loop=bot.loop)
- Make your `remind_user` async, and either make `create_reminder` and `cancel_reminder` async or remove await while executing them
- The `id` param..? If you want to cancel reminders later, create a random unique id, store it somewhere, and while cancelling the reminder use that id. Don't do `id="same_unique_id_which_you_used_while_adding_job"` this
Uhhhh?
I already saw doing this but i never found an explaination of what it does xD
Ohh shit I forgot to reply mention lol
@flat solstice ^ Reply to your last message
btw i want a trigger command to execute only 1/4 of the times
so like
if there's an event there's a 1/4 chance the bot will trigger
Possibility?
Yes
I want to use a copy pasta
Use the random module, generate random numbers, use conditionals
hmm
How would that work
Dude
Use random.randint, and then use conditionals
sure
If random_num == 2: return
Like this
Or just use random.choice and use bools, your wish
Yeah wait lemme try
Oki
hey would you suggest me to learn js to make a music bot or use python as i know it (for making music bot)
None
Music bots break youtube's TOS
Spotify?
And how do you plan to retrieve audio?
spotify_dl
Okay currently I'm working on slash commands so i thought i should learn more coz many of things are now copy/pasta
what is this
folder name music if link is not in music send import by !import link
!play music
The bot does not have the permission to kick users
Huh?
full traceback?
dw i got it
Check bots permission
yea fixed it
Okay
ty do
Pls read the error carefully before posting it here
that will raise BotMissingPermissions, and not MissingPermissions
Oh thanks for the explanation. And yeah I wasn't going to keep "same unique I'd" bit, I just haven't figured out what I'm going to make the ID be. I was thinking about making it be a auto incrementing column of my db but I can't find any docs for adyncpg related to incrementing columns
Make the ID a combination of str(user_id) + datetime.now().isoformat(). It'll always be unique unless the user is so fast to create two reminders in a nanosecond
Huh, that's not a bad idea, no wonder I didn't think of it
it was working before, but then how come after i changed the bot token and bot app, it doesnt work anymore
eol while scanning literal
pls help thx
The indent seems off i don't know tho
?
Are you using on message to make commands
yeah
Hmm can you show the whole on message
import discord
from discord.ext import commands
from discord.ext import tasks
import time
import random
import asyncio
import json
import os
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
version = discord.Activity(type=discord.ActivityType.watching, name=f"{len(client.guilds)} servers!")
await client.change_presence(status=discord.Status.online, activity=version)
#chatbot
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
client = MyClient()
client.run('bot token')
its too long, thousands of lines of code
Ah i see
cuz my discord accct recently got disabled so i had to create a new bot application
You should probably make actual commands instead of using on message
nah it would take too long
Oh wait
I'm stupid
Hmm
Have you tried removing the #bot command comment
Don't know if it will fix it
But that indent seems off to em
#bot command
You probably forgot an " somewhere
Maybe where you replaced the bot token??

Sorry I don't use discord.py 🛐

I mean
I am a PEP8 regulator
And also true would make an error
It should be True
thats not even python, its js

help
..........
😂
🤣
what to help
And also JavaScript should have a semicolon
@slate swan bruh
this is where it came from
it's optional

you dont really need it
by that I mean "what's wrong with that code"
not working no changes in channels
problem?
Ah
try set it to True not None
bruh but i dont want everyone to send msgs only roles linke family or verified should be able to do it
if i set it to true bro then even one which have muted will got burrrrrrrrrrrrr
so what should i do
use the channel var you defined in the loop
On YouTube

!resources consider this
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
sure
lets check
!resources
but, are you sure you didn't get any error before?
changed for 1 channel
you probably forgot to close a quote or something on the lines above
not all
Find this line in your code and check the syntax
changed only for 1 channel

bad indentation, you cannot use await outside the function
you forgot one )
anyone
check for errors
if you dont get one, maybe your error handler is blocking it
no error
hm then you miss the closing bracket for send
he wanted to say bracket

can someone send discord components link
!pip discord-components
true = True
hmm ill check
oh
eol while scanning literal error /discord.py/ pls help me thx
i knew that
my discord accct recently got disabled so i had to create a new bot application, it was working before, but then how come after i changed the bot token and bot app, it doesnt work anymore
Why making commands like this..
its from long time ago
Migrate then, it is not a good method
And I doubt the error is in those strings
how to fix?
Check this out https://tutorial.vcokltfre.dev/
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.
You are probably missing a closing bracket or a quote somewhere
But not in the strings you sent here
i hope i find it, thxs
whats a redirect url?
i need to add my discord.py bot in my server.
how do i publish bots?
pls help me :/
OAuth
do you mean verify?
how to do oauth
cuz my discord account got disabled and then recently i created new account.
then i dont know how to do it :/
Traceback (most recent call last):
File "C:\Users\giacomo.dimatteo\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 415, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\giacomo.dimatteo\PycharmProjects\GamingNetwork\lib\cogs\WildRiftTeams.py", line 77, in <module>
class WildRiftTeams(Cog):
File "C:\Users\giacomo.dimatteo\PycharmProjects\GamingNetwork\lib\cogs\WildRiftTeams.py", line 82, in WildRiftTeams
async def wr_team(self):
File "C:\Users\giacomo.dimatteo\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 647, in decorator
return InvokableSlashCommand(
File "C:\Users\giacomo.dimatteo\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 340, in __init__
options = expand_params(self)
File "C:\Users\giacomo.dimatteo\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\params.py", line 388, in expand_params
inter_param = parameters[1] if cog else parameters[0]
IndexError: list index out of range
importing cogs i have this error, how to fix it?
make your website, then make a path like https://mydomain.com/invite then add the link to Redirects
so i need to buy a domain?
before i didnt need to...
what are you trying to accomplish
before this i can add the bot directly to servers
you forgot the required parameter when registering a slash command
why now cannot? need own domain?
use the invite url
how do i find the invite url?
Your app -> OAuth2 -> URL Generator -> select scopes (usually Bot and Application Commands) & perms you need -> Copy Link (on the button of the page)
ok let me try it
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
emb=discord.Embed(title="Кик пользователя", description="**__Информация:__**", color=discord.Color.from_rgb(0, 255, 0), timestamp=ctx.message.created_at)
emb.set_footer(text="© Все права защищены The Greatest", icon_url=ctx.author.avatar_url)
emb.add_field(name="**Участник:**", value=f"**{member.name}** ({member.mention})", inline=False)
emb.add_field(name="**ID:**", value=f"**{member.id}**", inline=False)
emb.add_field(name="**Кикнул:**", value=f"**{ctx.author.name}**", inline=False)
emb.add_field(name="**Причина:**", value=f"Скоро", inline=False)
emb.add_field(name="**Канал:**", value=f"**<#{message.channel.id}>**", inline=False)
await ctx.reply(embed=emb)
Not working embed, why?
Guys guys, how do I get all the commands inside one cog after a command is invoked in another cog ;-;
bot.get_cog() then cog.get_commands()
ah oki, thankss
"Not working" isn't really helping
🤔
any error?
fixed
👍
No, the participant kicks, but the embed does not work, there is nothing in the console
Guys, I was able to run my bot for three months and then now somehow its not working
it doesn't send?
is this possible to happen
The owner of this website (discord.com) has banned you temporarily from accessing this website.</p>
Yes
how to let my bot display "add to server" button?
pls help thx, how to let my bot display "add to server" button?
How to get the Add to server button to your bot's profile:
- Go to https://discord.com/developers/applications/ and select your bot.
- From the side menu click on Oauth2 -> General
- Modify the Default Authorization Link section with a Custom URL or In-App authorization
Article: https://discord.com/blog/discord-bots-and-app-discovery-announcement
try putting a debug print before await ctx.reply(...)
Okay
where do you get that
Do someone know how i add a question? when i do it skips the question. Nothing in cmd
'Hvad hedder du IRL?',
'Hvor gammel er du IRL?',
'Hvor mange timer har du i FiveM?'
]
a_list = []
@bot.command(aliases=['staff-application'])
async def staff_application(ctx):
a_list = []
submit_channel = bot.get_channel(940207300885487636)
channel = await ctx.author.create_dm()
def check(m):
return m.content is not None and m.channel == channel
for question in q_list:
sleep(.5)
await channel.send(question)
msg = await bot.wait_for('message', check=check)
a_list.append(msg.content)
submit_wait = True
while submit_wait:
await channel.send('Din ansøgning er færdig - "send" for at indsende din ansøgning.')
msg = await bot.wait_for('message', check=check)
if "send" in msg.content.lower():
submit_wait = False
answers = "\n".join(f'{a}. {b}' for a, b in enumerate(a_list, 1))
submit_msg = f'Ansøgning fra: {msg.author} \nAnsøgning:\n{answers}'
await submit_channel.send(submit_msg)
await ctx.send("Din ansøgning er nu send afsted.")```
ok thanks it works
firstly time.sleep() is blocking, use asyncio.sleep() instead, second, what do you mean by "it skips the question"?
doesn't print?
did the member got kicked?
Yes
do you have an error handler?
No
client.add_cog(Antinuke(client))
TypeError: init() missing 1 required positional argument: 'headers'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/losoclientsdsdsds/events/bot.py", line 36, in init
self.load_extension(cog)
File "/home/runner/losoclientsdsdsds/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/home/runner/losoclientsdsdsds/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 623, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'events.AntiNuke' raised an error: TypeError: init() missing 1 required positional argument: 'headers'
wht to do
class Antinuke(commands.Cog):
def init(self, client, headers):
self.client = client
self.color = 0x2f3136
self.headers = headers
now try putting debug prints before .kick() and after it, and see where it stops
pls help
you can make so headers has a default value
Okay
how
hello everyone I am back
headers=None or something
ok
def init(self, client, headers=None):
self.client = client
self.color = 0x2f3136
self.headers = headers
this?
move self.headers above self.color
sure
lemme try
and the error seems like it’s from your setup function
not really needed, but okay
actully i wanted to make this work
@commands.Cog.listener()
async def on_member_ban(self, guild, user):
start = datetime.datetime.now().timestamp()
reason = "R Anti-Nuke | Banning Members"
async with aiohttp.ClientSession(headers=self.headers) as session:
async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
took = round((datetime.datetime.now().timestamp() - start), 3)
if r.status in (200, 201, 204):
logging.info("Successfully banned %s" % (user))
c = self.bot.get_channel(940206336824737804)
await c.send(f"Banned %s, took: {took}" % (user))
else:
logging.error(f"Could not ban %s" % (user)) ```
@slim ibex@visual island
you probably should only use this self.headers in the function it is needed so the constructor isn’t fucked
A wats that suppose to do?
Im curious
why making requests by your own?
At the Linux section of my repl
to make ban more fast cuz threaded nukers can nuke easily so i want to ban them faster , btw this doesnt ban the intruder what to do
Why don’t use you just use the discord api wrapper
idk how to
Trust me.
i got this faster
Learn
its probably just a ratelimit message but in raw html format
The api wrapper is so much simpler
it’s not?
coudnt find docs provide link
You don’t need docs
And I somehow also read this
There’s this YouTube series it’s super helpful
!d discord.Member.ban why not use this?
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
slower bro intruder makes 50 bans easily and then gets ban using threade nuker
what did you do?
how much field can i add to the embed
This is a wrapper function
In this series, we make a discord bot in python using discord.py version 1.0 also known as the rewrite branch of discord.py.
nothing much, I accidentally deleted the code but then was able to restore everything back to normal and then clicked run
it was ok from yesterday until few hours ago
It's slower? No.
i dont want member.ban()
yes indeed from my self experience
it was running fine for three months straight tho
^^
Ah okay, well that playlist will teach you discord.py
discord API has it's own latency, so it doesn't really depends on your code
i need answer fast
As many as you like I believe
25
ok thanks
Playlist from Lucas? Nice. Totally the best thing to learn from.
so i ma using api is discord v9 api the fastest?
till
okay so this is where I'm at so far```py
from apscheduler.schedulers.asyncio import AsyncIOScheduler
bot.scheduler = AsyncIOScheduler(event_loop=bot.loop) py
import asyncio
import logging
import typing
import discord
from discord.ext import commands
from discord.utils import get
from utils import checks
from datetime import datetime, timedelta
from typing import Optional, Union
from classes.converters import DateTime
#from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.schedulers.asyncio import AsyncIOScheduler
log = logging.getLogger(name)
class Reminder(commands.Cog):
def init(self, bot):
self.bot = bot
async def remind_user(self, member):
#send_message_to_user_about_reminder_time_completion()
user = await self.bot.get_member_guild(member.id, member.guild.id)
reminders = await self.bot.get_reminders(member.id, member.guild.id)
embed = discord.Embed(title = "Here's your reminder!", description = "{reminders[5]}", timestamp = reminders[6])
if user[9] == True:
await member.send(embed = embed)
else:
ctx_channel = await self.bot.fetch_channel(reminders[7])
await ctx_channel.send(embed = embed)
async def create_reminder(self, time, channel, user_time):
self.bot.scheduler.add_job(self.remind_user, 'interval', seconds=time, id=user_time)
await channel.send("Your reminder has been scheduled.")
async def cancel_reminder(self, reminder, channel):
self.bot.scheduler_remove_job(reminder)
await channel.send("Your reminder has been removed sucessfully.")
@commands.command(description = "Create a reminder.", usage = "send <server ID> <message>")
async def remind(self, ctx, time: DateTime, *, message: str):
user_time = str(ctx.author.id + datetime.now().isoformat)
await ctx.reply(f"Okay {ctx.author}, I'll remind you about your reminder `{user_time}` '{message}' in {time}")
await self.create_reminder(time, ctx.channel, user_time)
async with self.bot.pool.acquire() as conn:
await conn.execute("UPDATE reminder SET message=$1, time=$2, ctx_channel=$3 WHERE author=$4", message, time, ctx.channel.id, user_time)
@commands.command(description = "Create a reminder.", usage = "send <server ID> <message>")
async def delremind(self, ctx, reminder: str):
await self.cancel_reminder(reminder, ctx.channel)
def setup(bot):
bot.add_cog(Reminder(bot))```any of this looking immediately incorrect?
That is a very bad series
💀
shouldn't be, but the latest API should fit the best
i ws serching or it only pls provide me tht
keybord rip
+_+
Unless I’m blind, why do you import typing and not use it
anyways ```py
headers = { 'Authorization': f'Bot {self.bot.http.token}', 'Content-Type': 'application/json' }
is this fast
because a repurposed a template cog which includes it bc I use it quite often and I just hadn't got round to removing it yet bc i'm lazy
it really depends on the API latency as I said
you should remove unused imports. It populates the namespace with unneeded stuff
nothing to do with your code
class Antinuke(commands.Cog):
def init(self, client, headers = { 'Authorization': f'Bot {self.bot.http.token}', 'Content-Type': 'application/json' }):
self.client = client
self.headers = headers
self.color = 0x2f3136
self isnt identiied
show full error
It’s running on your local machine
wait
and how do I do that?
not there
good to know
unidentified name self
It’s already running in development when you run a flask or Django app
ouh but then I didnt push it to production at all
pass it in headers inside async with aiohttp.ClientSession()
ok
deploying it entails uploading all the code to a hosting service, getting SSL certificates, getting a domain, etc
lemme try
it’s just a warning saying to never push a localhost to production
shoudl i do self.client.?
ahh ok, but then somehow its not running and its saying I got temporarily banned somehow by doing nothing
depends on your var
What are you even doing?
ok
tbh at this point, I also dont know
Show code
theres literally nothing wrong with my code
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
one monute it works the other it doesnt
maybe it timed out
@slim ibex@visual islandthanks 4 ur helps it worked thanks a lot
np
Why are you going through the bare api anyway
to make fast response
🗿
Then don't use python
Speed isn’t everything
^
Its extremely slow compared to other languages
it matters like in threaded antinuke even the fastest nuker can bypass it with 5 bans btw normal antinuke it bypasses with 50 bans
everything in certain situations
yeah when ur making a fucking OS
it skips the question but takes all the others
Looks good to me. One thing in remind command is, reply to the user after creating the reminder, so in case if some error occurs, user won't get a fake message about their reminder being set
Then what should I use
emoji.url?
iirc 2.0 has some (a lot?) changes related to Asset and stuff
!d discord.Asset.with_static_format
with_static_format(format, /)```
Returns a new asset with the specified static format.
This only changes the format if the underlying asset is not animated. Otherwise, the asset is not changed.
there’s also Asset.with_format
Is Emoji also an asset?
uhmm
It's a property not callable
Excuse me my bad.
then how can I convert it into an asset
👍 And if I wanted to log the IDs for each task, what would be the best way to do that. I currently have a SQL database but would a nosql database be better suited to this type of use?
What’s the implementation again. If you mind me asking.
Ughh what
Like what’s your goal?
I want to make an addemoji command
And I want to convert the emoji into an asset url
you're using Guild.create_custom_emoji()
That takes bytes.
So you could use Emoji.read()
emoji.url will also return you the url of emoji.. I guess it should work for your application? Can you just share more code please?
if you have an emoji object already.
Uhmm wdym tbh this is the codeline
emoji = await ctx.guild.create_custom_emoji(image=await asset.read(), name=name)
@commands.has_permissions(manage_emojis=True)
async def addemoji(self, ctx, emoji: discord.Emoji,*, name=None):
asset = emoji.url()
if not name:
name = emoji.name
emoji = await ctx.guild.create_custom_emoji(image=await asset.read(), name=name)
await ctx.send(f"Emoji <:{emoji.name}:{emoji.id}> was added!")
Oh ok
let me have a try
@slate swan thank you so much bro
Np 👍
why are you guys spoonfeeding them
you gave no description on what emoji.read() does
.
Not sure if this is the place to ask, but does someone have any API's for currency? Like bitcoin, dogecoin and all of that?
Coinbase
Obviously if I said Guild.create_custom_emoji takes bytes and I told him to use emoji.read() where you’d pass image. He could more than likely infer that emoji.read() returns the emojis representation in bytes.
Does it require an API key or something?
Kick command, embed doesn't work, why?
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
emb=discord.Embed(title="Кик пользователя", description="**__Информация:__**", color=discord.Color.from_rgb(0, 255, 0), timestamp=ctx.message.created_at)
emb.set_footer(text="© Все права защищены The Greatest", icon_url=ctx.author.avatar_url)
emb.add_field(name="**Участник:**", value=f"**{member.name}** ({member.mention})", inline=False)
emb.add_field(name="**ID:**", value=f"**{member.id}**", inline=False)
emb.add_field(name="**Кикнул:**", value=f"**{ctx.author.name}**", inline=False)
emb.add_field(name="**Причина:**", value=f"Скоро", inline=False)
emb.add_field(name="**Канал:**", value=f"**<#{message.channel.id}>**", inline=False)
await ctx.reply(embed=emb)
you forgot 'ctx'
No?
🤔
What
Russia
why?
🤔
remove link n ban
!ban 306892975936372738 Steam scam
:ok_hand: applied ban to @wide pawn permanently.
He clicked on the link someone posted before
i try to become embed in function
????
@final iron its ok clicking but if u trade it gonna steal all ur items but gonna look like u get items
Yeah I know...
I pinged moderators for a reason...
I would like to convert this bot command into a function that i can call from another python file. When I call the function that the function sends the embeded message to a specific channel
# Embded message command shows the embded info
@commands.command(name="hello")
@commands.has_role("Admin")
async def hello(self, ctx: commands.Context):
embed = discord.Embed(title="productname", url="https://test.com", colour=0x87CEEB, timestamp=datetime.utcnow())
embed.set_author(name="retailer", icon_url="https://avatars.githubusercontent.com/u/16879430")
embed.add_field(name="test", value="test", inline=False)
embed.add_field(name="test", value="An inline field!", inline=True)
embed.add_field(name="Field 3", value="Look I'm inline with field 2!", inline=True)
embed.set_footer(text="Some footer!", icon_url="https://cdn.discordapp.com/emojis/754736642761424986.png")
await ctx.send(embed=embed)
Just fetch the channel then
Or make ctx a parameter in the function
or send as webhook
By using a webhook you can't send an embeded message right?
I'm pretty new to discord py. By fetching do you mean define the channel like this?
channel = commands.get_channel(channel_id)
await channel.ctx.send(embed=embed)
yes
u can send embeds as webhooks to
i guess that's much easier to do it. couldn't find any info how to do this
@slate swan do u mean u wanna send embed wen u run a python script, or u want same embed in another cog?
get a user with only his mention without using converters?
Just want to send embed when running from another pythons script
if i understand u correct, then i would check webhooks u need like 2lines of code
I was using webhooks but couldn't sent embeds that why i changed to discord py. but if its possible i will for sure use webhooks again
aight hold on one sec
@slate swanhttps://pypi.org/project/discord-webhook/#basic-webhook
from discord_webhook import DiscordWebhook, DiscordEmbed
webhook = DiscordWebhook(url='your webhook url')
# create embed object for webhook
# you can set the color as a decimal (color=242424) or hex (color='03b2f8') number
embed = DiscordEmbed(title='Your Title', description='Lorem ipsum dolor sit', color='03b2f8')
# add embed object to webhook
webhook.add_embed(embed)
response = webhook.execute()
``` an example of embed
Niceee
Thanks this is where i was looking for. Well at least learned a lot about discord bots 😄
whats cool with webhooks is you can change avatar and names like it would look like diffrent bots etc
going to play with it
Guys how do i format the cooldown for commands in minutes and not seconds
i cant find it in API or im just blind
msg = "Hello WOrld"
nick = "This is a bot!"
thumb = "https://url_to_an_avatar_here"
webhook = DiscordWebhook(url="https://discord.com/api/webhooks/....",
content=msg,
username=nick,
avatar_url=thumb,
rate_limit_retry=True
)
``` @slate swan
if you want diffrent names n avatars
i think you will need to make ur own function for that
@compact ruinhttps://stackoverflow.com/questions/775049/how-do-i-convert-seconds-to-hours-minutes-and-seconds here are few examplpes
i think most common is like those
def sec_to_hours(seconds):
a=str(seconds//3600)
b=str((seconds%3600)//60)
c=str((seconds%3600)%60)
d=["{} hours {} mins {} seconds".format(a, b, c)]
return d
print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']
print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']
def time_format(seconds: int):
if seconds is not None:
seconds = int(seconds)
d = seconds // (3600 * 24)
h = seconds // 3600 % 24
m = seconds % 3600 // 60
s = seconds % 3600 % 60
if d > 0:
return '{:02d}D {:02d}H {:02d}m {:02d}s'.format(d, h, m, s)
elif h > 0:
return '{:02d}H {:02d}m {:02d}s'.format(h, m, s)
elif m > 0:
return '{:02d}m {:02d}s'.format(m, s)
elif s > 0:
return '{:02d}s'.format(s)
return '-'
sory kinda offtopic...
im confused how i make a bot that has currency
a ik someone told it to me yesterday but im still confused
👍
Thanks buddy
Managed to make my own
a does someone have 24/7 music bot that i could use on my server ?
Is there any way of banning users based on if they’ve been marked as spammers?
use hydra
anyone know some free websites I can use for API?
For what
Helpp
isn't there a way to code idents like /n? I keep doing >>> text in my code but I'm pretty sure there's a easer way right?
!d discord.ext.commands.Bot.change_presence @velvet haven
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
Mind giving an example?
Anyone know a way to check if a user is marked as a spammer?
But with discord.py not disnake
Not possible
>>> text would be
text
and i thought i saw someone mention here the other day that there's a way to code that with something like/nnewline but I can't remember what it was, if they even gave a example
Damn
you cannot do anything new with discord.py
Disnake works fine right now?
!pypi rin is also a great choice
you heard wrong
Yes I’ve heard about hikari
It always did
I would like u to check out rin too
hikari if you're able to rewrite your complete bot
Disnake if you don't want to
Why Rin?
When you say rewrite
Are we talking like
Change some variables or re do everything
You would have to change literally everything
It got some good non mainstream API implementations which I like tbh. No harm in checking it out at least haha
Hikari is not a fork, it's a complete different library
and so is rin
So I’d have to re do everything if I go with either
If I do decide to migrate
Which would you guys recommend?
Hikari or rin
I would prefer u to checkout both of them. Rin is still a WIP, but can be used for some bots, hikari is a complete framework
my name's biased
Lol
I see
I think Il just move to disnake
For what I’m doing it doesn’t seem like there’s enough reason to rewrite
Sure, Disnake is a good choice as well
Is it possible to add a hook to all commands in discord.py? Essentially i just want to log how often each command gets called.
You could just make a variable called count
Then another command that will return all those variables for each command
ctx.author will get the user that sent the message for example
and you can do ctx.author.mention and it will mention them
How expensive is calling get_server or get_channel to get the respective Guild or Channel objects from an ID? I have IDs stored in my Redis DB but I can't serialize the objects nor do I really "need" to serialize them either, I'm trying to think of alternative methods of storage, perhaps even something like a nested in memory dictionary as I imagine that will be my most lightweight and performant option. Any ideas?
I created a custom exec command and it works, but it eats all the errors if there are any for some reason, which means it does nothing when there's an error
https://pastebin.com/BXtzvn6B
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
It just gets an object from cache, so not very expensive
*get_guild btw
Okay 🙂 So it isn't making an API call to do that? Excellent!
I have another question as well
regarding the use of a get_prefix function, take for example the following:
async def get_prefix(client, message):
if not message.guild:
return commands.when_mentioned_or(client.default_prefix)(client, message)
curr_server = await helpers.get_local_server_object(message)
prefix = curr_server.prefix
return commands.when_mentioned_or(prefix)(client, message)
Is this get prefix called every time a command is sent? My reason for asking is if I were accessing a Database to get prefix it might be expensive to call, is that the case or is it in memory?
Hmm, okay, that could potentially get expensive
yep
I'm going to have to think about how to do it in that case 🙂 Thank you!
However, I can take advantage of that as well, I could have some logic that gets just the prefix from say redis db but if the server isn't already in the redis DB it can do that work so that I can guarantee elsewhere that any server sending commands has a server reference in Redis DB, and can also use that to do initial setup for in memory storage stuff
so it might be a blessing in disguise 🙂
That way I don't have to check for that anywhere else since it is guaranteed to be handled before any command is even registered
Thank you 🙂
a simple way would be create a simple empty dictionary with ur bot variable ie bot.prefix_cache = {} and store prefixes in that, so what u need to do next is check for this dict if it has data related to that guild then send it else fetch from ur db and add it to that dict. This is a nice and easy implementation of caching which many people use
Databases are built to be queried a lot so it’s fine, if you still want to save processing power you may cache previous queried prefixes in-memory via a mapping of guild id to prefix key pair
Another good choice is having a redis caching layer which many large companies do
I was considering that, but it could get outdated as well
I am using Redis as my primary DB so I imagine it will be relatively expensive since it can make atomic requests and just get the intended value
How would it get outdated?
I will use caching anyway to track tasks either way
Just make sure to update the cache when a user uses a command to set the prefix
I will eventually have other applications that are able to change the prefix though
but maybe I could set up something like a redis stream and have a listener for changes to the prefix so that it updates
so I could work around that as well
If your other applications are able to access the in-memory cache that would be ideal, but you could probably also do that
They will all access my API which will access the Redis DB datastore but I can make it so that when the API writes to the Redis DB it also creates an item in the redis stream and the other apps can react to that or not if not needed
not working autorole?
What is it doing when you attempt this?
can someone help me get this 🇾 into a reaction?
I keep getting an error of "emoji argument must be str, Emoji, or Reaction not NoneType."
asking me?
Looks like add_roles wants a list
emoji = client.get_emoji(940273239920377896)
emoji = discord.utils.get(client.emojis, name=':regional_indicator_y: ')
ive tried those two
so try [role]
okayy
nvm ill just use this 👍
Actually, I might be mistaken, I think the *roles just makes it into a list
still not working
per a little searching, this appears to be a potential solution
instead of passing in role pass in the following:
discord.utils.get(user.guild.roles, name=role)
async def addrole(ctx):
user = ctx.message.author
role = 'role' #change the role here
try:
await user.add_roles(discord.utils.get(user.guild.roles, name=role))
except Exception as e:
await ctx.send('Cannot assign role. Error: ' + str(e))
ctx.message.author is probably not necessary, ctx.author I think suffices in current dpy
but give that a try and see if that works for you 🙂
simply just
Message.add_reaction(":regional_indicator_y:")
should work
Ignoring exception in on_member_join Traceback (most recent call last): File "C:\Users\Atk\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) TypeError: on_member_join() missing 1 required positional argument: 'user'
but
not user.mention but self.user.mention?
no..?
was a question
also @hollow plank you have 2 on_member_join events, just combine them
ah ok, it should be user.mention if you are mentioning a user
im trying but
i tried something but still not working
this is my first time with cogs
can somebody help me bros
whats not working
try using get_role
ha?
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
@hollow plankkinda fun you have long await with send() in same lines, but defines member_role = "member" instead of name="member"
man i tried hundred times, hundred different variations
👀
cogs
Help plss
still not working
u know...
does it launch
yes
how you know
maybe its not problem in code
What happened tho
no errors just nothing bro
then it don't launch
:c
add a print statement to the start of the listener
print working :c
or make sure you have all of these:
init with every requirement
setup function outside of cog
load the cog
yes
bruh
then surely an error happened mid-code and your error handler ate it up
not possible
how
As long as u don't override on_error, errors are not eatable in events
What's the issue tho
._.
got an error handler?
no error

ahh
.
no
damnit
idk what to do
Kick command, embed doesn't work, why?
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691)
async def kick(ctx, member: discord.Member, *, reason=None):
await member.kick(reason=reason)
emb=discord.Embed(title="Кик пользователя", description="**__Информация:__**", color=discord.Color.from_rgb(0, 255, 0), timestamp=ctx.message.created_at)
emb.set_footer(text="© Все права защищены The Greatest", icon_url=ctx.author.avatar_url)
emb.add_field(name="**Участник:**", value=f"**{member.name}** ({member.mention})", inline=False)
emb.add_field(name="**ID:**", value=f"**{member.id}**", inline=False)
emb.add_field(name="**Кикнул:**", value=f"**{ctx.author.name}**", inline=False)
emb.add_field(name="**Причина:**", value=f"Скоро", inline=False)
emb.add_field(name="**Канал:**", value=f"**<#{message.channel.id}>**", inline=False)
await ctx.reply(embed=emb)
firstly, any error?
There is no error, the person kicks, but there is no embed
do u have an on_command_error event?
No
can u even reply with embed?
i mean is that even possible overall
why not
🤔
@slate swantry your reply with just a simple string
should not
ofc
I did and with await ctx.send the embed was not displayed either
how do I hide the jishaku cog from displaying in my help command?
Helpp
you can just ignore the jishaku cog while adding the embed fields
I haven't subclassed Jishaku ^
okay
@slate swanone error that happens with embes can usally be urls, but would't know why it cant show avatar url
are you sue it prints a correct url?
Remove url?
you can basicly just do
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691)
async def kick(ctx, member: discord.Member, *, reason=None):
print(ctx.author.avatar_url)
return
to see if it gives a valid url
Ok
i dont know correct but i know some always confuse avatar_url, and avatar.url
i think the later is correct tho
SyntaxError: invalid non-printable character U+200A
what lol
🤔
nvr copypasta from discord!
just write it as i show not copy it
but i start think its cause avatar_url is wrong its avatar.url
Console:
https://cdn.discordapp.com/avatars/578931699686178817/ab47c4fbc78d6b9241bbe8a913f73e01.webp?size=1024
@honest vessel
Error in another?
@slate swanmy eyes cant spot any errors, hard without errors helping what to look for
If your dealing with urls couldnt you just throw this into the browser and if it brings up the image it should be correct
image came out ok
Then the url should be ok
Sorry im kinda jumping in the middle, whats the overall issue? Or a message link to the start to play catchup
.
My suggestion would be to just go through emb and slowly add each embed 1 at a time and trying it until it stops working. And whichever you add that stops it from working is the problem
🤔
When something works and doesnt throw an error but also isnt working as a person intends its very difficult to just be able to provide why it isnt working. The best thing to do is just manually troubleshoot /test the code to see where and then why its not doing what it should
heck yeah, https://discord.gg/disnake we just got our vanity :3
hey
Python 3.8.2 (default, Feb 26 2020, 02:56:10)
Replit: Updating package configuration
--> python3 -m poetry add aiosqlite discord aiofiles aiohttp
Using version ^0.17.0 for aiosqlite
Using version ^1.7.3 for discord
Using version ^0.8.0 for aiofiles
Using version ^3.8.1 for aiohttp
Updating dependencies
Resolving dependencies...
SolverProblemError
Because no versions of discord match >1.7.3,<2.0.0
and discord (1.7.3) depends on discord.py (>=1.7.3), discord (>=1.7.3,<2.0.0) requires discord.py (>=1.7.3).
Because discord.py (1.7.3) depends on aiohttp (>=3.6.0,<3.8.0)
and no versions of discord.py match >1.7.3, discord.py (>=1.7.3) requires aiohttp (>=3.6.0,<3.8.0).
Thus, discord (>=1.7.3,<2.0.0) requires aiohttp (>=3.6.0,<3.8.0).
So, because repl-python3-apollon depends on both discord (^1.7.3) and aiohttp (^3.8.1), version solving failed.
at /opt/virtualenvs/python3/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
237│ packages = result.packages
238│ except OverrideNeeded as e:
239│ return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
240│ except SolveFailure as e:
→ 241│ raise SolverProblemError(e)
242│
243│ results = dict(
244│ depth_first_search(
245│ PackageNode(self._package, packages), aggregate_package_nodes
exit status 1
Package operation failed.
what is that
pls ping me
Looks like it requires aiohttp version 3.8.0 or lower and you have 3.8.1 if im reading this correctly
how do i change that
Redownload it with the specific version
hi im trying to get all members in a role using role.members and im certain the name is correct. however when printed it will just return a empty list
[]
this is my code
tried using a for loop on it but that didnt work either, is there anything wrong
@bot.command()
async def test(ctx):
role1 = discord.utils.get(ctx.guild.roles,name="telescience")
print(role1.members)
no no that parts correct, i just removed the space because it looks better for me but ill try it
expression cannot contain assignment
thats what it says when i do that
so im pretty sure thats ok but it wont return anyone from the telescience role and im in that role
Gimme a moment to check the docs
If this how it is returns an empty list. Try moving the .members to the end of "rolel =" line and just print rolel
Looking at the docs guild.roles returns a list of all the server roles. Try getting rid of the ,name="telescience"
And see if it still prints it
Everyone as in all the people that have it or litterally just @ everyone
yea i got it working now
turned out i forgot to turn on member intents since this is a seperate test bot i used for experimenting new stuff with my friend
thanks for the help anyway
Ah, sorry i wasnt much help. Im still learning some of these things 😅
ok, i need someone to review this code for me. this is a calculator code for my bot and i am using eval. however, someone is scaring me that people can exploit it, even if i put float or int. pls let me know how it is. i am using nextcord
await interaction.response.defer() #goes to thinking stage
result=float(eval(calculate))
try:
calculation = Embed(title="Result", color=0x00FFFF)
calculation.add_field(name=calculate, value=result)
await interaction.followup.send(embed=calculation) #answer
except:
invalid=Embed(description="That is not a valid calculation")
await interaction.followup.send(embed=invalid) #no numbers or some fuckery```
Yo! anyone know how I would add overwrites to a channel? e.g. there are already specific ones but I want a new member to be able to view the channel
How would I add them to the channel while remembering the old overwrites
self.client
ohh okay
I have no idea sorry
pass self to your function
it wont work for me like the tutorial in the docs
how
every function of a class



