#discord-bots
1 messages · Page 470 of 1
tho the first issue i see glaring is naming
so a client.run i am assuming
i wonder who in the world is suddenly tellling EVERYONE to do client = commands.Bot because i suddenly see EVERYONE coming here using wrong naming
how come it has to be bot, its just a variable name
naming
pep 8
if you don't follow good naming conventions now, god knows wherever you don't either
learn yourself the good habits of writing clear and easily maintainable code
if i name every variable Xn and n being any random number, well it works. it's "just a variable" as you say, but good luck trying to debug you code once it doesn't work.
yeah of course i understand and agree to that, that just how python variable works, its just i am confused why you can not use client as a variable name
Client according to naming conventions in dpy implies you use discord.Client where bot implies you use commands.Bot
How do you access the member ID of the user that used a slash command? The solutions i've found on stack overflow are just giving me the member ID of the bot's response to the slash command.
What are you using for slash commands? As in what library?
So discord_slash
ye
<Message id=887099213148741712 channel=<TextChannel id=761025438986010665 name='new-joiners' position=21 nsfw=False news=False category_id=457657319564771338> type=<MessageType.new_member: 7> author=<User id=327491696692822016 name='asapglocky' discriminator='2238' bot=False> flags=<MessageFlags value=0>>```
what's the best way to take this text and extract just the member id from it
How do I make it so text is hyper linked to a url in a embed?
Should be a ctx.author_id
Sadly the module doesn’t have documentation so I had to dig into the source on GitHub
That looks to be you printing a message instance
So for a embed it would look liike
description=f"Click to get free pizzza"
?
You don’t take the values from that print
!d discord.Embed
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
You just use the attribute
em = discord.Embed(title = 'text', url = 'url')
kinda like this
As you can see author is part of a message object. So just get message.author. and from there you can get the .id attribute of author
Now Do i have to rewrite my embed as i have it or i put that up in imports and then do {url} in the description of my code i have?
That’s not the hyperlink they meant probably
That’s one way yes, but the rest all uses text
wait
What if i just do
url = 'Pizza pizza'
then do {url}
in the description where i want it?
wait no
idk what i was just thinking
Pizza pizza
Ah yes the great “[Object object]”
?
JavaScript jokes
:c
lol
async def on_ready():
await client.change_presence(status=discord.Status.do_not_disturb, activity=discord.Game('bot stuff'))```
it wont work
so how do i get the hyper link in the embed though cus i cant find anything
u trynna make the bot post link on command?
DO NOT change presence in on_ready
Do NOT make any discord api call in on ready. NEVER
why?
damn
lmao
On ready fires before the client is ready and can lead to cache corruption if you make api calls. Also on ready can fire multiple times and can get you api banned
Luckily there is a solution
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
@commands.command(name="setstatus")
async def setstatus(self, ctx: commands.Context, *, text: str):
await self.bot.change_presence(activity=discord.Game(name=text))
See how it has an activity option in the docs? Use that
That is a safe way to set a status right as you come online
bro i need to take a shit and u made my but cheecks close so hard i think im having a stroke
Lmao
;/
So do you knwo anyway to add the hyper link into a embed?
Cus im lost
Okay it’s not THAT bad but just don’t do api calls in on_ready because that’s just bad
What I said is like worst case scenario but it is possible
So add that where in this
@commands.command(name="ssuvote")
async def ssuvote(self,ctx):
embed = discord.Embed(title = f"Server Start Up Vote", description =f"Vote With the ✅ mark if you plan on attending." "\n" "\n" " Vote with a ❌ if you can not join." "\n""\n" "If you vote with the check you must join when ssu opens if not you will be warned!" "\n" "\n" "** If you get warned and join the Sesh then you can dm a admin to get it taken away!**")
embed.set_thumbnail(url = 'https://images-ext-2.discordapp.net/external/jftnVFITYRGaMwbf6aY7Qutqp6Q_2gA4v72nXBbpALg/%3Fsize%3D512/https/cdn.discordapp.com/icons/857793161370533938/c38dde5d462235e12a3e10a2dc789dc6.png?width=461&height=461')
msg = await ctx.send(embed=embed)
await msg.add_reaction("✅")
await msg.add_reaction("❌")
await ctx.message.delete()
class MyClient(discord.Client):
async def on_ready(self):
print('Ready too be used!') here is another one
I want it to become the title when i change the title
Just part of the string you want to set it
It’s just in the string
So i want the title to change so i do
f"[Server start up vote]{pizza.cem}
?
You forgot something
What
@valid niche can u check dms real quick lol
Assuming pizza.cem is a link
I don’t do dm support
You’ll be silently ignored
😦
from discord.ext import commands
#discord.Intents.all()
intents = discord.Intents.default()
client = commands.Bot(command_prefix='!', intents=intents)
@commands.command(name="Do.Not.Disturb")
async def setstatus(self, ctx: commands.Context, *, text: str):
await self.bot.change_presence(activity=discord.Game(name=text))
@client.command()
async def clear(ctx, ammount=10):
await ctx.channel.purge(limit=ammount)
here was the api ban thingie can u add it?
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'you':
await message.channel.send('Shalom, mf hows it hanging')
client = MyClient()
client.run('token')```
!codd
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.
can u add the api ban thingie can u fix it?
!codd
ah forgot
Also naming please
wdym?
Read from here
A few messages down should explain enough
So hey you have your commands.Bot
Just like this
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Oh what do I see. In the constructor you can do activity= to safely set an activity upon logging in?
That seems rather convenient
When i did
embed = discord.Embed(title = f"[testing pizza](pizza.com)")
it did
[testing pizza]
(pizza.com)
Make it a full valid URL
it was
this is what i really printed
Server Start Up Vote
Vote With the ✅ mark if you plan on attending.
Vote with a ❌ if you can not join.
If you vote with the check you must join when ssu opens if not you will be warned!
If you get warned and join the Sesh then you can dm a admin to get it taken away!
See how it turns blue?
damn link
I want the words to be the hyper link so when i click the words Server Start Up that brings me to the link
Not the link
I dont want to see the link i want it to be so when i click those words it takes me to the link
Whatever I don’t judge (unless you watch Lucas, use replit or any combination of the both)
I dont
this is for friends and somthing to do
So is there a way to hyper link the words Server Start Up so when i click them i get the link?
I assume the field you used doesn’t support hyperlinks then
What feild
In an embed only certain parts accept hyperlinks and I forgot which ones
I do believe title and footer didn’t allow hyperlinks
It’s not subtle…but it is effective :D
hey there, im coding a discord bot. I want to make it be able to have a different theme like red and blue ect could someone help me with that?
Different theme? Red and blue? Who what where?
like
i could have 1 theme and design and stuff
Theme where what when?
and i can put the prefix then theme and make it a different theme
Theme what?
does that make sense?
okay so like a different look
Different look as in?
different embed colour different gif ect
You need to be more precise, exact and detailed with your question
Well you decide the embed color when you create it
For a gif well if you send a gif you pick what gif to send
yes but i want to be able to change it without editing the code itself and just typing lets say the prefix is .
i would type .theme 2 and it could change to a different embed colour
Can somebody link me the page for BucketType in the documentation I can't seem to find it
Have you heard of: variables?
AttributeError: 'ComponentMessage' object has no attribute 'message'
i know a tiny bit about variables
!d discord.ext.commands.BucketType
class discord.ext.commands.BucketType```
Specifies a type of bucket for, e.g. a cooldown.
Well it says there is no message.message
This is a string idk if that matters or if the string is turned into an object automatically
Which I find a valid thing because I don’t see a reason to have message duplicated
There is no string
There is only message in that error
hi, how can I detect when an image is sent & then do things with it (like post it in another channel or download it)
messages = await ctx.channel.history(limit=20).flatten()
for msg in messages:
print(msg.message)```
i'm trying to get the author of the message
msg.message gives me that error
message.author
ctx.author?
sure
ah
object has no attribute 'message'
ih
oh
well what does this code do in the first place ;what are you trying to acheive
ah
hah my bad
doh
@client.command()
async def select(ctx):
await ctx.send("This is a new feature!",
components=[
Select(placeholder='Select Something!', options=[SelectOption(label='A', value='a'), SelectOption(label='B', value='b')])
]
)
while True:
interaction = await client.wait_for("select_option")
if interaction.values[0] == "a":
await interaction.respond(content=f"You Clicked the `A` value!")
elif interaction.values[0] == "b":
await interaction.respond(content=f"You Clicked the `B` value!")
why do i get interaction failed
Is there a way to ping a role in a embed?
Or from what im reading it has to be outside of the embed
await ctx.send("code for role mention")
@commands.command(name="ssuvote")
async def ssuvote(self,ctx):
embed = discord.Embed(title = f"ServerStart Up Vote", description =f"Vote With the :white_check_mark: mark if you plan on attending." "\n" "\n" " Vote with a :x: if you can not join." "\n" "\n" f"[```Click here to get a link to ERLC```](url)" "\n""\n" "If you vote with the check you must join when ssu opens if not you will be warned!" "\n" "\n" "** If you get warned and join the Sesh then you can dm a admin to get it taken away!**")
embed.set_thumbnail(url = 'https://images-ext-2.discordapp.net/external/jftnVFITYRGaMwbf6aY7Qutqp6Q_2gA4v72nXBbpALg/%3Fsize%3D512/https/cdn.discordapp.com/icons/857793161370533938/c38dde5d462235e12a3e10a2dc789dc6.png?width=461&height=461')
msg = await ctx.send(embed=embed)
await msg.add_reaction(":white_check_mark:")
await msg.add_reaction(":x:")
await ctx.message.delete()
ok
@bot.command(aliases = ['ask8', 'magic8'])
async def 8ball(ctx, *, question=None):
random_answers = ['No Doubt', 'My sources tell me YES', 'You can rely on that', 'Better not tell you', 'Reply Hazy, Try Again', 'Nah, I wouldn\'t keep my hopes high on that', 'Highly Doubtful', 'Hell No']
if question == None:
await ctx.reply('Ask a question so that i can reply to it smh')
return
embed=discord.Embed(description=random.choice(random_answers), colour = discord.Color.blurple())
embed.set_author(name = question, icon_url = ctx.author.avatar_url)
await ctx.send(embed=embed)
it says invalid syntax in line 2, can someone please help?
i'm just trying to simply ban a member by their ID #. how can i do this
do i have to loop through the whole ctx.guild.members list to find the id
random_answers = ['No Doubt', 'My sources tell me YES', 'You can rely on that', 'Better not tell you', 'Reply Hazy, Try Again', "Nah, I wouldn't keep my hopes high on that", 'Highly Doubtful', 'Hell No']
@bot.command(aliases = ['ask8', 'magic8'])
async def _8ball(ctx, *, question=None):
responses = random.choice(random_answers)
if question == None:
await ctx.reply('Ask a question so that i can reply to it smh')
return
embed=discord.Embed(description=responses, colour = discord.Color.blurple())
embed.set_author(name = question, icon_url = ctx.author.avatar_url)
await ctx.send(embed=embed)
try this
Then you would have to call it by putting a underscore.
^^^
You can do that, but, inside bot.command() put name="8ball"
So you don't have to call it by the underscore
how can I detect when an image is sent & then do things with it (like post it in another channel or download it)
You should be able to just use ctx.guild.get_member(id) and ban them that way
get_member(user_id)```
Returns a member with the given ID.
You can mention but it won’t trigger a push notification or a red number pop up
Either through role.mention, which produces the raw format <@&id> or you can fill in that format yourself with the ID
on_message, then see message.attachments
bot.get_user(id)/fetch_user(id)
await guild.ban(user)
i know
How can i make a command ping the author of who wrote the command?
I think? or I know
async def on_message(msg):
_list = ['cringe','bean']
if any([i in msg.content for i in _list]):
await msg.delete(msg)
await msg.reply("stop")
doesn't work
!dcc
TypeError: delete() takes 1 positional argument but 2 were given
in on_message
await msg.delete(msg)
await msg.delete() only
kk
how would I say, if message is message.attachments, print or repost in another channel
doesn't work
in on_message
await msg.delete
TypeError: object method can't be used in 'await' expression
await ctx.message.delete()
message is message.attachments?
what is this issu
That deletes the message
my bot doesnt run!
await message.delete()
This is my purge command
await msg.reply(content=...)
So I have this code here:
interaction = await client.wait_for('button_click', timeout=timeout - time.time())
await interaction.respond(content = 'You Clicked A Button')
If I don't include the second line, a button click will result in saying interaction failed
Does anyone know how to make it so the button does not require a response? (this uses discord-components button btw)
wait i dont have one in this bot lmao
yea that works but ctx.channel.purge seems to have broken for my bot
so how do i put it
It’s not returning any error
@client.listen() async def on_message(msg): _list = ['cringe','bean'] if any([i in msg.content for i in _list]): await msg.message.delete() await msg.reply("stop")
what the issue
this doesn't work
its a mistake
Don’t show your key lmao
usually you put it though
@bot.command(aliases = ['ask8', 'magic8'])
async def 8ball(ctx, *, question=None):
random_answers = ['No Doubt', 'My sources tell me YES', 'You can rely on that', 'Better not tell you', 'Reply Hazy, Try Again', 'Nah, I wouldn\'t keep my hopes high on that', 'Highly Doubtful', 'Hell No']
if question == None:
await ctx.reply('Ask a question so that i can reply to it smh')
return
embed=discord.Embed(description=random.choice(random_answers), colour = discord.Color.blurple())
embed.set_author(name = question, icon_url = ctx.author.avatar_url)
await ctx.send(embed=embed)
it says invalid syntax in line 2, can someone please help?
await msg.reply(content="stop")
@flint cipher
oh ok
didnt see lel
its because of the async def 8ball
but how do i make it delete the message after
you can't have a number starting @flint cipher
what's msg.message...
lol
the message itself is msg
so how 2 fix
remove the .message
when I say await channel.send(f'{message.author}: {message.attachments}') it gives me a link which leads nowhere
@median isle i think you need an on_ready
@bot.event
async def on_ready():
print('Bot Ready. Logged in as ' + bot.user.name)
link?
so just msg.delete
yeah
sure
why isn't this working?
await ctx.channel.purge(limit=int(arg1) + 1)
any errors?
when I post an image, then the bot catches it as a message.attachment, it says filename=filename and gives a link which gives an error
there are no issues with that statement, it is probably other parts of your code
oh, it adds a series of %56%3% after the link.. is there any way to remove them?
what are you trying to do exactly?
All the other code seems to be working fine. It just stops running code right after that line
when an image is posted, I want the bot to snag that image and post it in another channel
if message.attachments: # empty list is False
await bot.get_channel(1234).send(f"{message.author}: {message.attachments}")
how can i remove the percemtages at the end of the link?
str.replace("%", "") but it would probably break the link
File "/home/ec2-user/.pyenv/versions/3.7.9/lib/python3.7/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "/app/moddy/cogs/quiz.py", line 59, in on_raw_reaction_add
msg = await channel.fetch_message(payload.message_id)
File "/home/ec2-user/.pyenv/versions/3.7.9/lib/python3.7/site-packages/discord/abc.py", line 1132, in fetch_message
data = await self._state.http.get_message(channel.id, id)
File "/home/ec2-user/.pyenv/versions/3.7.9/lib/python3.7/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
what missing perm can cause this?
how can i get the bot to pick a random text channel then get the id from it
always getting termed for no reason smh @pure reef
read_message_history
thx
random.choice(c.id for c in Guild.text_channels)
@bot.command()
@has_permissions(administrator=True)
async def clear(ctx, arg1=None):
global prefixs
embed20 = discord.Embed(title=f"You have deleted {arg1} messages!",
color=0x1597BB)
embed20.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
embed21 = discord.Embed(title=f"Usage: {prefixs}clear `integer`",
color=0x1597BB)
embed21.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
embed21.add_field(name="An error occured",
value="The process has been `terminated`.",
inline=True)
try:
if arg1 == None or int(arg1) == 0:
await ctx.channel.send(embed=embed21)
return
await ctx.channel.purge(limit=int(arg1) + 1)
message = await ctx.channel.send(embed=embed20)
time.sleep(3)
await message.delete()
except:
await ctx.channel.send(embed=embed21)
@clear.error
async def clearerror(ctx, error):
if isinstance(error, CheckFailure):
embed21 = discord.Embed(
title=f"You must be an admin to use this command!", color=0x1597BB)
embed21.set_author(name=ctx.author, icon_url=ctx.author.avatar_url)
embed21.add_field(name="An error occured",
value="The process has been `terminated`.",
inline=True)
await ctx.channel.send(embed=embed21)
else:
return
still no error i can find
nvm somehow it works again 🤣
is there a way to fetch everything beyond the .png part of the link and delete it?
do you mean prevent spamming or?
Oh
how can i make it so i have an argument but its not required
@bot.command()
async def welcfooter(ctx, message):
try:
if message is None:
await ctx.send("Cleared welcome footer")
db[f"{ctx.guild.id} footer"] = ""
else:
pass
del db[f"{ctx.guild.id} footer"]
db[f"{ctx.guild.id} footer"] = message
await ctx.send(f"Set **{message}** as welcome footer")
except:
pass
``` isnt working
i thing the is None: is wrong tho
You could try saving a list of past messages and compare them. Make sure it's from the same author
async def welcfooter(ctx, *, message=None)
it took that long for you to type a simple thing
oh well
not much info but i'll take it
then , ```py
if message is None:
Sorry dude was doing something
correct
thx bro
ok
my problem is its putting None into the db
because you didn't return it
explain plz if you dont mind
if you don't return it, it's going to continue
learned sum new thx
ofc
How do I make the bot check what kind of message it is for example pinging people/sending images
message.mentions length and message.attachments length
How can I make a bot that send messages to a specific channel?
Example: ,up #test Note
And it send to #test channel
alright how can I check if a message is a link if possible
I'm not 100% sure, because I've never done this, but you might be able to typehint the argument as a TextChannel, and it will pass a discord.TextChannel object
Just a hunch
Ye tysm I will figure it out, somehow 
get your channels id and makea variable associated with the id like this channel = bot.get_channel(id)
then await channel.send('')
So I put (id= channel id?)
no
how can i make my bot leave a server? i do not owned
get the guild ID, catch the guild object and leave
how can I check if a discord message contains a link
Regex....?
yeah idk what that is mate
when ever i try this i got an error
@commands.command(hidden=True)
@commands.is_owner()
async def leave(self, ctx, guild: discord.Guild):
await self.bot.leave_guild(guild)
await ctx.send(f"I Had Left guild: {guild.name} ({guild.id})")```
to_leave = self.bot.get_guild(id)
await to_leave.leave()
try this but i am not sure
@commands.command(hidden=True)
@commands.is_owner()
async def leave(self, ctx, guildID: int):
guild = await self.bot.get_guild(guildID)
await guild.leave()
await ctx.send(f"I Had Left guild: {guild.name} ({guild.id})")```
this should work
im stupid dont add self to to_leave.leave()
^^^
you can make a bot.event that detects a key thing in the message like http but im sure there is a better solution
get_guild don't need to be awaited
@commands.command(hidden=True)
@commands.is_owner()
async def leave(self, ctx, guildID: int):
guild = self.bot.get_guild(guildID)
await guild.leave()
await ctx.send(f"I Had Left guild: {guild.name} ({guild.id})")
i think you dont add await to guild
you can try this @lyric moat
yeah
Only fetch methods need to be awaited
Worked Thanks
np
how i stop it from doing this?
@client.command()
@commands.has_permissions(manage_messages=True)
async def poll(ctx, user: discord.Member = None):
if user is None:
await ctx.send(f"{ctx.author} you must mention a user to do that!")
else:
icon_url = ctx.author.avatar_url
pollEmbed = discord.Embed(title = "New knowed poll", description = f"**Is Knowed/UnKnowed**\n\n - **Knowed**\n - **Unknowed**",colour=0x2f3136)
pollEmbed.set_thumbnail(url=f"")
pollEmbed.set_footer(text = f"Poll requested by{ctx.author}")
await ctx.message.delete()
poll_msg = await ctx.send(embed = pollEmbed)
await poll_msg.add_reaction("")
await poll_msg.add_reaction("")```
One question... How can I add roles using the role ID?
how can I check if a discord message contains a link
Do what?
Stop sending the embed when no user is mentioned?
add discord.Role typehint to your role argument , it automatically converts the id to role
how do i send message in a channel by knowing the channel id only?
Hey guys, i'm trying to turn the binary from gateway.discord.gg to human readable format
I've tried a bunch of stuff, but have no idea how to do this
b'\xc2\x1b\x1a86\x83\x91\xd7\xe6\xa2\xee\xcc\xc1h\x911Zd\xd0\xad\xc8\x00\x00\x00\x00\xff\xff'
An example of binary received
discord devs and discord api. thay have bot for discord server too
!d discord.Client.get_channel
get_channel(id)```
Returns a channel with the given ID.
I believe the documentation provides you with a way to get that data back into readable data.
Use this and .send
ok
The discord docs have a thorough walk through and even provides an implementation in python
https://discord.com/developers/docs/topics/gateway#encoding-and-compression
An int
ok
@bot.command(name='play', aliases=['p'])
async def play(ctx,url):
voice_client = ctx.message.guild.voice_client
if voice_client.is_connected():
else:
server = ctx.message.guild
voice_channel = server.voice_client```
i want it to ignore the next part if the first part is true, how would i do that?
(sorry idk how to format it to python i'm slow)
i'm still kinda bad at python lmfao
use return in the if
if <something>:
return```
i can't create invite for bots for dscord
They might have a link in their info channel :3
Channel = client.get_channel(id)
ok
can i use the sqlite and aiosqlite both at the same time
im making per server prefixes i know it only with sqlite
but if there any solution regarding per server custom prefix with aiosqlite then pleasse tell me that also
is it possible to tag a channel by it's id in dpy? for ex i have the id of python-general and i want to tag the channel like this #python-discussion is it possible to do this by my dpy bot?
if there is a docs page for that?
yes its possible
if you want mention channel by context then ctx.channel.mention
check your indentaion @slate swan
import asyncio
import base64
import secrets
from json import load
import aiohttp
ws_key = base64.b64encode(secrets.token_bytes(16)).decode('utf-8')
headers = {
'Pragma': 'no-cache',
'Origin': 'https://discord.com',
'Accept-Language': 'en-US,en;q=0.9,es;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Sec-WebSocket-Key': ws_key,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/93.0.4577.63 Safari/537.36',
'Upgrade': 'websocket',
'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
'Cache-Control': 'no-cache',
'Connection': 'Upgrade',
'Sec-WebSocket-Version': '13',
}
async def go():
from main import buffer, inflator
session, ws = None, None
try:
with open('first_message.json') as file:
to = load(file)
session = aiohttp.ClientSession()
ws = await session.ws_connect(url='wss://gateway.discord.gg/'
'?encoding=json&v=9&compress=zlib-stream',
headers=headers)
msg = await ws.receive()
print(msg.data)
await ws.send_json(to)
async for msg in ws:
print(msg)
buffer.extend(msg.data)
print(inflator.decompress(buffer))
finally:
if ws:
await ws.close()
if session:
await session.close()
if __name__ == "__main__":
asyncio.run(go())
import zlib
ZLIB_SUFFIX = b'\x00\x00\xff\xff'
# initialize a buffer to store chunks
buffer = bytearray()
# create a zlib inflation context to run chunks through
inflator = zlib.decompressobj()
The error:
Traceback (most recent call last):
File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 52, in <module>
asyncio.run(go())
File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 42, in go
print(inflator.decompress(buffer))
zlib.error: Error -3 while decompressing data: unknown compression method
I tried this earlier, @paper bane @wispy spade
Could be how you're combining the data, if you do it separately, it seems to work just fine.
Do what separately? Would you mind elaborating?
Decompress the data separately instead of decompressing it all at once as you're doing it now.
print(inflator.decompress(buffer)) I thought this line would decompress them msg by msg?
Also, I've taken just the bytes, tried to decompress that, and got the same error message
hmm, maybe in the for loop, try resetting the buffer back to a bytearray() after you're done with that msg.
is it on_guild_remove or on_guild_leave
both are there
what do you want it for?
when it leaves a server it sends a embed to a specified channel
im guessing its leave but i could be incorrect
!ctx
something like that
What did you need though.
Thing is, it doesn't even decompress the first message
how do i get an error of a cm like this
@bot.event
async def on_member_join(member):
try:
a = db[f"{member.guild.id} welc"]
t = db[f"{member.guild.id} footer"]
h = bot.get_channel(a)
l = db[f"{member.guild.id} msg"]
embed = discord.Embed(description=l,color=discord.Color.blurple)
embed.set_footer(text=t)
await h.send(embed=embed)
except:
await h.send(f"**ERROR, this error is being reported to the developers, it will be fixed in a range from** `1.5 - 6 days`")
Weird, any errors with that?
The same one, this:
Traceback (most recent call last):
File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 52, in <module>
asyncio.run(go())
File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\lafft\PycharmProjects\DS\ws_handler.py", line 42, in go
print(inflator.decompress(buffer))
zlib.error: Error -3 while decompressing data: unknown compression method
hmm
Anyone know how can I let the bot send messages to a specific channel on channel mention?
yes as the command arguments type hint one to arg : discord.TextChannel and then do arg.send()
what do you mean
Wait I'll try
i'm trying to get the error of the event if there is one
Thank you so much, it worked
if embed sending isn't available, if the bot doesn't have access to the channel, or if the db stuff.
@frosty prairie code?
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandInvokeError):
log = bot.get_channel(887187090037702656)
await ctx.send(f"```py\n{error}```")
await log.send(f"**GUILD ID; {ctx.guild.id}**\n ```py \n{error}```")
``` nothing would send
then do py except discord.Forbidden
i got it
for one cmd at least
embed = discord.Embed(description=l,color=discord.Color.blurple)
``` whats wrong abt this
Why blurple
like the color
Ohh
file=discord.File(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\king_of_diamonds.png')
embed = discord.Embed(title='..')
embed.set_image(url="attachment://king_of_diamonds.png")
message = await ctx.send(embed=embed, file=file)
await message.add_reaction('🤙')
fetch = await message.channel.fetch_message(message.id)
print(fetch.reactions)
def check(reaction, user):
return reaction.emoji == "🤙", user == ctx.author
msg = await bot.wait_for('reaction_add', check=check)
embed2= discord.Embed(title='..')
embed2.set_image(url="attachment://king_of_diamonds.png")
file2 = discord.File(r'C:\Users\ogtla\OneDrive\Desktop\python\cogs\king_of_diamonds.png')
await message.edit(embed=embed2, file=file2)
it sends file but while editing, it gives error tho same file
what error
should i embed all that stuff then it sends ?
what?
i suggest you keep it ,since servers might wanna do like (emojis + nitro giveaways )etc , unless its a private bot
how can I check if a discord message contains a link or emoji
how do i get the role spot of the bots top role vs a role
like if the bots role isnt over another role
nvm
did you get it?
just made my bot run forever, feeling good
how can i add guild icon in embed?
in the footer..??
at the top of embed
ohh ok
you can get the link of the guild's icon by ctx.guild.icon_url
oh ok lemme try
idk
alright
nope doesnt work in (title="")
that is title
are you trying to putting the embed as thumbnail or image ?
Here like this
embed.set_author(name=ctx.guild.name, icon_url=ctx.guild.icon_url)
i was about to ask can i use set_author
But lemm try
:) alright
Nope it doesn't show the guild icon
Here is the results
Here is the code
Ignore the red underline it's a bug
Does the guild have an icon
Not the default one
If it doesn't have one then it will return None
Try adding some random pic to your guild's icon
oh shoot my bad, the server doesnt have an icon
That's why
tysm for telling
Yw
thanks @NotMrBugcat#3246, @Kraots#3999
sorry was afk
:) np
in embeds, i want to use the color #090303 do i just do |
color = "#090303"?
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
..
.
Simply replace the # to 0x
Hi guys, who can help me to build opensea discord bot?
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
while using mongo motor with discord.py is this required
import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(do_insert())
result ObjectId('...')
so many typos
its not bad
?
is it a test command im assuming right?
i see
i usually test my bot with a ping command
it looks like this
@slate swan who's alt are you?
@pure reef termed or sum idk i got phone locked
o
your indentation
^^^
i did every time i did it it does this
lets see the code
yep
we'll try to help
i suggest you use
alright
!paste
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.pydis.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.
!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.
discord intends sometimes broken
yeah you right
It should be
e1 = discord.Embed()```
!d discord.Embed
class discord.Embed(**kwargs)```
Represents a Discord embed.
`len(x)` Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
Alr Lemme Try
e1 = discord.Embed(title="embed1", description="a really exciting embed")
e2 = discord.Embed(title="embed2", description="a really exciting embed")
e3 = discord.Embed(title="embed3", description="a really exciting embed")
ask
How to fix this
Got This
code?
needs to be in the same line
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
InteractionType.ChannelMessageWithSource like this
did you install python and the packages needed for your bot?
on python.org or the microsoft store?
Same Line As?
move ChannelMessageWithSource up with the InteractionType. so it would make InteractionType.ChannelMessageWithSource
there was saying to install so i dowloaded from phython.org
@client.command()
async def ban(ctx, member: commands.MemberConverter, reason=None):
try:
if not reason:
embed=discord.Embed(description=f'You have been banned in **{ctx.guild.name}**.')
await member.send(embed=embed)
await ctx.guild.ban(member)
embeder=discord.Embed(description=f'{member} was banned.')
await ctx.send(embed=embeder)
else:
embed=discord.Embed(description=f'You have been banned in **{ctx.guild.name}** for {reason}.')
await member.send(embed=embed)
await ctx.guild.ban(member)
embeder=discord.Embed(description=f'{member} was banned.')
await ctx.send(embed=embeder)
except:
embed=discord.Embed(description='Member can\'t be banned.')
await ctx.send(embed=embed)
``` This is my ban command as of now and it works but if your the server owner like me it still DMs you even if you didn't get banned. How do I fix this?
Hmm I did
its python.org not phython.org
or was it a typo
does it work?
But Every Time I tried it gives this
that only
Maybe use a comma?
its there
No thats a dot
how to import discord
pip install discord.py
o nvm
then in code type import discord
Whats the error again
Well I tried it and the red camed off
pip : The term 'pip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- pip install discord.py
-
+ CategoryInfo : ObjectNotFound: (pip:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
but ended up with this
Revert it
go to your command prompt
and type pip install discord.py
if that does not work you do not have pip installed or python installed
how to go to command prompt
Why When I put a . at
type=InteractionType.ChannelMessageWithSource,```
it gives red line to the code but when i try
```py
type=InteractionType,ChannelMessageWithSource,```
it takes off error
python3 pip install discord.py
``` try this
I said dont??
how to get a users about me or banner thing
fetch it then send the banner
don't know how
await bot.fetch_banner(id) ig
go to search bar on windows and type cmd and click enter
So how i fix this now?
then what do i do with the banner id
why are the indents so fricking big
not the banner id the user id
wait
pip' is not recognized as an internal or external command,
operable program or batch file.
did you do this from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
@lyric moat
no
put that in the beginning of the code
did u try what I said?
they took out InteractionType.
done
U cant get about me's yet but banners you can just fetch the users banner in 2.0 and send it
yup Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
got this
Did u install the package yet?
scratch that how do i see how many people are offline, online, and how many bots
i tried put that but it would not work should i put it in the cog too?
Member.status ig
!d discord.Member.status
status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
pip install discord-buttons
y put it in a cog if there's still errors?
put that in terminal
this doesn't show me who's offline
not sure about status but with amount of members, you use intents
nor who's online
i keep getting this..
it is saying Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
how do i get the offline members and online members that's all i need to know.
intents
for one guild
how do i get the date when my server was created? guild.created_at?
yeah you can do one guild with intents
okay enabled them
can someone help?
ctx.guild.created_at
!d discord.Guild.created_at
created_at```
Returns the guild’s creation time in UTC.
did you do pip install discord-buttons in terminal?
u don't have it installed probably
it's repl idk if they work in repl
idk if discord components work in repl
forgot that was there
they do lmfao
It's not an IDE without a shell/terminal
my head is in many directions
click space once or twice
indentation
any code example?
!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
the if message.content isn't in the function
No use the docs
@bot.event
async def on_message(message: discord.Message):
if message.guild is None and not message.author.bot:
print(message.content)
print(message.author)
embed = discord.Embed(title="Confirm Mail creation",description="This system is used for reporting bugs,reports concerning to the moderators.",color=0x3DFD1E)
a=await message.author.send(embed=embed)
await a.add_reaction('\u2705')
await a.add_reaction('\U0001f6ab')
def check(reaction, user):
return user == message.author and str(reaction.emoji) in ['\u2705','\U0001f6ab']
reaction, user = await bot.wait_for('reaction_add',check=check)
print(reaction.emoji)
why does't it print the reaction the user reacted on?
how to use it?
try making a test command ```py
print(ctx.guild.created_at)
Please reset your token you just showed it to everyone
guild = ctx.guild
await ctx.send(guild.created_at)
how? 💀
where?? thats on repl?
Theres a button that says shell thats approximately 100 pixels
you should see it
can't u just do os.system("pip install (whatever)")
nope i do not see it
Do u know what terminal is?
thank you
why is it arranged in this shitty way?
^^^
help me File "c:\Users\prani\Desktop\Nova Client\Nova Client.py", line 1, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
PS C:\Users\prani\Desktop\Nova Client>
alr i see it
By default
pip install discord
Download discord.py first?
i want to change default
anyone ^^
@lone gulch
so i put pip install discord-buttons
in the shell?
u need to do this pip install discord
in ur terminal
in terminall ?
yah
yes terminal
like cmd
yes in the shell
how do i fix this?
@lone gulch did u install discord.py tho?
use description
this what i got
that's what i do most of the time
bro...
try it now ig
done!
indents
u have all the wrong shit outa place
u wrote the last part outside the on_message function
just tab
i use if statements like
if str(reaction) == 'emoji':
print('cross')
elif str(reaction) == 'emoji':
print('tick')
yes i highly recomend it to see the error before asking
It's a simple indent error you should be able to fix that yourself pretty easily
it is extremely to fix
oh
ok lemme try
the whole thing does not even respond
by how
It said not command found test
undefined name reaction
Have you tried installing discord-components from the package manager?
did u forgot the parentheses
and the name is test
if message.content.startswith('Good afternoon'):
await message.channel.send('Good afternoon! I am Newton’s Bot and nice to meet you!')
await message.channel.send(random.choice(note))```
highlight that and press tab
Did you restart/reload the cog after making the changes
@stark hearth
it keeps showing red line and it does not show error but just not answer the command
BRUHHH I JUST FINISHED MONEY HEIST NOW I GOTTA WAIT TILL DECEMBER THIRD
Did you import them
import what?
i only watched like 2 seasons
Bruh
and just forgot about it
huh
is there any way to fix this without using description?
You need to import them from discord-components
inline kwarg?
what is even that? 😂😂
I thought he meant the date 💀
But why use a 3rd party lib that's breaking iirc instead of just using the master version which also had selects 😟
a kwarg for add field
add a kwarg called inline and set it to a boolean ig
yeah
Have you tried reading the docs maybe
try this
try:
reaction, user = await bot.wait_for('reaction_add',check=check)
print(reaction.emoji)
except:
await ctx.send('something')
my indents are suffed ik
ok thanks
can u give me link of the docs page pls
!d
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
add_field(*, name, value, inline=True)```
Adds a field to the embed object.
This function returns the class instance to allow for fluent-style chaining.
@stark bobcat dont add the asyncio.TimeoutError my bad
i was looking at my bot
yep i realised
ok
Hey @slate swan!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
post it in https://paste.pythondiscord.com/ then share
yeah
do
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
if message.content.startswith('Good afternoon'):
await message.channel.send('Good afternoon! I am Newton’s Bot and nice to meet you!')
await message.channel.send(random.choice(note))
add @client.event to your on_ready
also for the last line it needs to be client.run(os.environ['DISCORD_TOKEN'])
not client.run(os.getenv('DISCORD_TOKEN'))
the second part under on message event yeah
im stupid lol
but just for organization, you can do that
does it work @slate swan
take your time
im asking after this i need to sleep for an exam
error?
like this ^^^
send that part after running the script
like it is running but the bot is not responding?
!d os.getenv it's there
os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesn’t. *key*, *default* and the result are str.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3.10/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3.10/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3.10/library/intro.html#availability): most flavors of Unix, Windows.
Not saying anything to u dw
You dont have @client.event
yeah i know but it needed to be []
Also thats the wrong event
^^^ @slate swan
No....?
does it???
That be wrong
os.getenv()
os.environ[]
yeah im stupid
!d os.environ
os.environ```
A [mapping](https://docs.python.org/3.10/glossary.html#term-mapping) object representing the string environment. For example, `environ['HOME']` is the pathname of your home directory (on some platforms), and is equivalent to `getenv("HOME")` in C.
This mapping is captured the first time the [`os`](https://docs.python.org/3.10/library/os.html#module-os "os: Miscellaneous operating system interfaces.") module is imported, typically during Python startup as part of processing `site.py`. Changes to the environment made after this time are not reflected in `os.environ`, except for changes made by modifying `os.environ` directly.
This mapping may be used to modify the environment as well as query the environment. [`putenv()`](https://docs.python.org/3.10/library/os.html#os.putenv "os.putenv") will be called automatically when the mapping is modified.
im dosing off rn my bad
how did message come in this....
Yeah
😂
you right lol
on_message
^^^
oh nevermind im so stupid
Show yr load function
You loaded it right?
Uhhh?
i was using the normal bot instead of testing bot

im stupid lol
Haha
use bot.run(os.getenv('DISCORD_TOKEN'))
how do avoid microseconds in timedelta?
it does not print the reaction
@bot.event
async def on_message(message: discord.Message):
if message.guild is None and not message.author.bot:
print(message.content)
print(message.author)
embed = discord.Embed(title="Confirm Mail creation",description="This system is used for reporting bugs,reports concerning to the moderators.",color=0x3DFD1E)
a=await message.author.send(embed=embed)
await a.add_reaction('\u2705')
await a.add_reaction('\U0001f6ab')
def check(reaction, user):
return user == message.author and str(reaction.emoji) in ['\u2705','\U0001f6ab']
try:
reaction, user = await bot.wait_for('reaction_add',check=check)
print(reaction.emoji)
except:
pass```
@client.command()
async def coinflip(ctx):
faces = ["heads", "tails"]
choice = random.choice(faces)
embed = discord.Embed(color=0x000000)
embed.add_field(name="\U0001fa99 Spinning...",
value="`Please wait`", inline=False)
new_embed = discord.Embed(color=0x000000)
new_embed.add_field(name="\U0001fa99 Coinflip",
value=f"<@!{ctx.author.id}>, you got **{choice}**", inline=False)
wait = await ctx.reply(embed=embed, mention_author=False)
await asyncio.sleep(2)
await wait.edit(embed=new_embed)```
did I make anything wrong? bc it's choosing tails everytime .-.
im sorry @stark bobcat @slate swan but i need to sleep
Everything is correct
ok
im dosing so much lol
it's choosing tails everytime 😔
It's choosing tails cz random module likes tails 😂
lmfao
@flags.add_flag('-n','--number')
@orbs.command()
async def use(self,ctx,message,**flags):
orbs=flags['number']```
why i m getting key error number in this
bye bye
bye
you need event on message?
Which flags lib u using? Can I know? (Not related to yr problem)
how do i avoid printing microseconds in time delta?
discord.ext.flags
ye
Ah ok thanks
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
await message.channel.send("Leave. Me. Alone. Dumbass.")
await message.add_reaction(emoji="\U0001f1e9")
await message.add_reaction(emoji="\U0001f1ee")
await message.add_reaction(emoji="\U0001f1ea")
return
if message.author == client.user:
return await client.process_commands(message)
if message.author.bot:
return await client.process_commands(message)
ctx = message.channel
await client.process_commands(message)```
this is on bot mention
from my bot
oh
i am trying to print the reaction the user reacted on
hm
is there a way to make discord say "bot is thinking"
like with slash commands
defer the response?
does discord.py support interactions??
@maiden fable sry for the ping but do u know how to fix this
Lemme see
no like:
coinflip
bot: please wait...
discord: bot is thinking...
bot: you got tails
Bro...
You are eating every error in that except of yours. What do u expect?
oh
so
just use await ctx.send(random.choice(faces))
should i do like
I like sytle
except Exception as e:
print(e)?
thats on u lmamo
Yea
ok
wait = await ctx.reply(embed=embed, mention_author=False)
async with ctx.typing():
await asyncio.sleep(2)
await wait.edit(embed=new_embed)```
this triggers typing but doesn't stop after the sleep @maiden fable
ye no errors and does not print reaction user reacted on
Move the edit inside the async with
Weird
before or after sleep?
After lol
\😬
check like this
Yea
str(emoji)=="😬"
Yea
so im thinking of making a whois/ui command for my bot, and i was wondering if theres a way to see how many messages theyve sent in a server without a db?
you will have to iterate over all messages and need to check the author, that process can take a long time
if its for a personal server depending how old it is. i suppose. if its for a public bot, not possible. or i guess...it technically is, but that'll take weeks
Just use a db 
Ayo how do you make a command Case Insensitive?
You can make all commands case insensitive instead with the case_insensitive=True kwarg in your bot constructor
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Okay
so im trying to make something which Dyno bot has in the whois command... how can i get a user's permissions (if they have it) ?
perms = []
key_perms = {
'administrator': 'Adminstrator',
'ban_members': 'Ban Members',
'kick_members': 'Kick Members',
'manage_guild': 'Manage Server',
'manage_channels': 'Manage Channels',
'view_audit_log': 'View Audits',
'manage_messages': 'Manage Messages',
'manage_nicknames': 'Manage Nicknames',
'manage_roles': 'Manage Roles',
'manage_permissions': 'Manage Permissions',
'manage_webhooks': 'Manage Webhooks',
'manage_emojis': 'Manage Emojis',
'mention_everyone': 'Mention Everyone',
'deafen_members': 'Deafen Members',
'mute_members': 'Mute Members',
'move_members': 'Move Members',
}
``` i have this much rn... now what??
!d discord.TextChannel.permissions_for
permissions_for(member)```
Handles permission resolution for the current [`Member`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member "discord.Member").
This function takes into consideration the following cases...
theres a has_permissions decorator as well
!d discord.ext.commands.has_permissions
discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
not just for a channel
that will return the members permissions for the text channel
yes but its for cmds like ban, kick
do you want guild wide?
yes
!d discord.ext.commands.has_guild_permissions
discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions"), but operates on guild wide permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage").
New in version 1.3.
this
Check the permissions of the members top_role
they key permissions section?
yes
guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use either [`permissions_in()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Member.permissions_in "discord.Member.permissions_in") or [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership and the administrator implication.
hmm
Using a command, how would I cycle through a list 1 item at a time? I can't seem to get itertools cycle to work
maybe i'm doing something wrong ;-;
You could just keep a pointer/index into the list and increment it each time ig
@commands.command(help='[Starts a given task.]',aliases=['ff'])
async def funfact(self,ctx):
iteration = itertools.cycle(["A", "B", "C!"])
await ctx.send(next(iteration))
a for loop?
no i dont want to have the entire thing display at once..
use a for loop
I want to be like $ff and it gives me "A" then $ff again and i get B
oh
I dont want all 3 at once
Well, you define the cycle within the command, so it'll point at the first item all the time
DDefine it out of it and should be fine
How would I define it?
I've never used itertools before.
put the iteration variable as an attribute of the class an re-use it
Yep. ty ^_^ it was just in the wrong spot
you need to save a state of cycle
Easy peasy
How do I get my embed to go on the next line
Like currently its like
Current Ping
??Ping Aliases: ping or PING
I want
Current Ping
??Ping
Aliases: ping or PING
\n (new line character)
So i just do that in my code?
Correct
oki
if len(message.mentions) > 5:
#if message.author.guild_permissions.manage_messages:
#return
await message.delete()
role = discord.utils.get(message.guild.roles, name="Muted")
await message.author.add_roles(role, reason="Automod muted for Mass Mention (5m)")
embed = discord.Embed(title=f"AutoMod Muted {message.author.name}",
description=f"reason : Spamming", colour=discord.Color.red())
log_channel = self.bot.get_channel(863000643303374920)
await log_channel.send(embed=embed)
await asyncio.sleep(1)
await message(
f"{message.author.mention} Don't Mass Mention! You Have Been Muted in Server for 5m")
await asyncio.sleep(300)
await message.author.remove_roles(role, reason="Automatic unmute for spam")
message.mentions is not working?? or not triggering?
define 'not working'
no erros.
Theres no reason that would error? hahahaha
Have you tried printing its length, or the list itself
bro there are reasons it might create errors but it took me some 20m to get here but still not able to find why not triggeering this while other Automod works fine
if statements don't throw errors if there false, but hey. Not my place
Have you tried printing its length, or the list itself
umm let me try printing : )
try a smaller number. like 1? also the bot can't mute you.
so maybe it is triggering. try just having the bot in line 1 after the if, say "Triggered!"
so like this?
perms = []
full_perms = member.guild_permissions
key_perms = {
'administrator': 'Adminstrator',
'ban_members': 'Ban Members',
'kick_members': 'Kick Members',
'manage_guild': 'Manage Server',
'manage_channels': 'Manage Channels',
'view_audit_log': 'View Audits',
'manage_messages': 'Manage Messages',
'manage_nicknames': 'Manage Nicknames',
'manage_roles': 'Manage Roles',
'manage_permissions': 'Manage Permissions',
'manage_webhooks': 'Manage Webhooks',
'manage_emojis': 'Manage Emojis',
'mention_everyone': 'Mention Everyone',
'deafen_members': 'Deafen Members',
'mute_members': 'Mute Members',
'move_members': 'Move Members',
}
for permissions, user_perms in key_perms.items():
if permissions in full_perms:
perms.append(user_perms)
if perms:
em.add_field(name='Key Permissions', value=', '.join(perms), inline=False)
Why wont this work? ```py
async def funfact_add(self,ctx, *, ff, type):
i try and run it and it says missing argument.
inside a command signature you cant have two keyword arguments
I can.
async def funfacts_settings(self, ctx, setting = None, update = None):
```works.
there are no keyword arguments there
i'm getting the user id when i'm mentioning the bot through discord.py embed. Please help
you can't do that in titles
So i'd have to either move 'type' to before the 'ff' or figure something else out?
i'm doing client.user.mention in an embed. Doesn't that work?
send the code
it should
no, if it's in the title
you can only have a single keyword argument inside a command
you have to make either argument a positional
@slate swan
i did not load my test cog where it was there LOL.....ik i am dumb 🥲
help :/
well ofc it doesnt work on footers
btw bot can mute me
When i do this I get Powered By <@userid>
it was working earlier :/
How do I use underlines on embeds??
in the footer?
mentions does not work ig
so.... how do i do it?
So the thing is,
I'm trying to use a function outside the main function, inside a class.
functions.py
class functions(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def account_stats(self, access_token: str, accountId: str):
gtResult = self.getPowerLevel(items)
Level = gtResult[0]
return Level
...
def Power(self, items):
...
return Power
main file
from tests.functions import functions as fn
class stats(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def stats(self, message, userName=None,):
...
stats = await fn.account_stats(access_token=access_token, accountId=account_id)
...
But that way, it would give me the error: ```TypeError: account_stats() missing 1 required positional argument: 'self'
but if I add `self`, like this
`stats = await fn.account_stats(self, access_token=access_token, accountId=account_id)`
I will instead get this error
AttributeError: 'stats' object has no attribute 'getPowerLevel'
Am I using the `self` wrong or?
Using cogs btw
umm in footers only text is there not mentions
guild_permissions is iterable that returns a tuple. u can unpack it and make ur own list of perms that are True
perms = ctx.author.guild_permissions
for perm, value in perms:
if value is True:
# add it to a list
Then at the end display that list
oh hi
so what i did is wrong?
a little. close though
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/message.py", line 1262, in remove_reaction
await self._state.http.remove_reaction(self.channel.id, self.id, emoji, member.id)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
I'm trying to remove reaction from a message
bot does not have the permissions (discord perms) to remove it
how do i give the bot perms?
Now to get some ~fun facts~
File "c:/Users/User/Downloads/discord bot/main.py", line 4, in <module> from music_bot import Player ImportError: cannot import name 'Player' from 'music_bot' (c:\Users\User\Downloads\discord bot\music_bot.py)
``
import discord
from discord import player
from discord.ext import commands
from music_bot import Player
intents=discord.Intents.default()
intents.members=True
bot=commands.Bot(command_prefix="!",intents=intents)
@bot.event
async def on_ready():
print(f"{bot.user.name}is ready to use.")
async def setup():
await bot.wait_until_ready()
bot.add_cog(Player(bot))
bot.add_cog(Player(bot))
bot.run("")``
go the server settings, roles, and change the permissions of the role that the bot has
i gave the bot admin perms