#discord-bots
1 messages · Page 493 of 1
how the hell dubai?
idk lmao
I miss changing server regions tbh
It was a good feature but It had no use except VCs and such
Would sb be kind enough to help with #help-mango
Ok
guys, i want to make kinda of an automatic message sender, but in this case is my account that will send the messages, how do i do it? the whole ideia is , every 3 hours a command is sent to a certain channel on my server
!rule 2
2. Follow the Discord Community Guidelines and Terms Of Service.
Automating normal user accounts (generally called "self-bots") outside of the OAuth2/bot API is forbidden, and can result in an account termination if found.
If you want to keep your account, don't do that
And we won't help you for that either
its on my private server, can that be a problem?
It doesn't matter where you send it
Automating things on your account is overall not allowed
And I'm pretty sure farming currency, pokemons or similar things of bots using this way will get yourself banned from using the bot ever again
That's against the TOS as Krypyton has pointed out
for chan in discord.guild.channels:
await chan.set_permissions(role,send_messages=False)
await ctx.channel.send("All channels have been paused pls wait...")```
The error ```AttributeError: module 'discord.guild' has no attribute 'channels'
!d discord.Guild.channels
property channels: List[GuildChannel]```
A list of channels that belongs to this guild.
read this ^
shows error
you have to define guild
oh
i know of this
channel = await find_channel(member.guild)
?
is that a command
idk its on stack
what
@bot.command()
@commands.has_permissions(manage_channels=True)
async def unpause_all(ctx, guild : discord.Guild):
role = discord.utils.get(ctx.guild.roles, name="new role")
for chan in guild.channels:
await chan.set_permissions(role,send_messages=True)
await ctx.channel.send("All channels have been unpaused")```u meant this ri8?
why are you doing guild : discord.Guild?
to get list of channels(correct me if im wrong)
just remove that arg and only keep ctx
and get the guild by doing ctx.guild
like how you did for the getting the role
ok
it showsdiscord.ext.commands.errors.MissingRequiredArgument: guild is a required argument that is missing.
did you remove the guild argument?
yes
@bot.command()
@commands.has_permissions(manage_channels=True)
async def unpause_all(ctx):
role = discord.utils.get(ctx.guild.roles, name="new role")
channels = discord.utils.get(ctx.guild.roles)
for chan in channels:
await chan.set_permissions(role,send_messages=True)
await ctx.channel.send("All channels have been unpaused")```
@bot.command()
@commands.has_permissions(manage_channels=True)
async def unpause_all(ctx):
role = discord.utils.get(ctx.guild.roles, name="new role")
for chan in ctx.guild.channels:
await chan.set_permissions(role,send_messages=True)
await ctx.channel.send("All channels have been unpaused")
you have not defined channel.
do i doesnt it send the message in the channel where it was called
it sends me error:
listss = ['a', 'b', 'c']
if listss in message.content.lower():
str(message.content).lower() maybe
!e
string = 'apples'
listss = ['a','b','c']
if listss in string:
print('error')```
import discord
from discord.ext import commands
from discord.utils import get
bot = commands.Bot(command_prefix="F!", intents=discord.Intents(messages=False, guilds=False))
@bot.command()
async def addcyberrole(ctx):
print("1")
member = ctx.message.author
if member.id == "550322163190857729":
print("2")
role = get(member.server.roles, name=":space_invader:Cyber-General:space_invader:")
await bot.add_roles(member, role)
print("3")
else:
await ctx.send("nope")
bot.run(token)```
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: 'in <string>' requires string as left operand, not list
it doesnt respond smh
@sweet merlin , you'd have to loop over the lists and check if the the value is in the message content
for i in lists:
if i in message content : etc
does 2 print ?
thanks
i think its because the intents in ur bot , i dont think thats how you define it and you have messages = False
did you copy this from somewhere ?
from the Documentation
btw my bot is verified and yet not accepted for intents
how do you expect the bot to read the messages when you have them as false ?
@Cog.listener()
async def on_message(self, ctx):
if ctx.content == ("b!setup"):
for channel in ctx.guild.channels:
if channel.name == 'logs':
await ctx.channel.send('Logs have already been set up')
return
channel = await ctx.guild.create_text_channel('logs')
for channel in ctx.guild.channels:
if channel.name == 'logs':
self.log_channel = self.bot.get_channel(channel)
await ctx.channel.send("logs have been set")
so guys i have this problem setting up logs if i type this in two servers then its setting up the id to the other server and the logs are only going to the other servers channel is there any way to store the ids and then check the guild to see if the id matches with the server the logs have been set up
use discord.ext.commands
wait will that fix my problem
what about a json file
Nope
Json isn't for storing data
fix what?
use a dict or a database
hmm
why would they put it in cache tho? That flushes everytime the bot shuts down or restarts.
db is the best choice here 👌
hey
can anyone help me with a join commnd?
i want my bot to join the vc
not to play music or someting, just to join
await ctx.author.voice.channel.connect()
it doesnt join
no
try pip install discord.py[voice]
ok
are you in a vc tho?
yeah
any idea how do you make your command accept multiple arguments with spaces?
@bot.command(aliasses=[])```
no
Wdym?
That’s not what he wants
not ike that?
Args
are you asking how to multiple (*, arg)s?
Like (ctx, arg1, arg2)
@bot.command()
async def foo(ctx, *, a1, a2, a3):
...
...
I think
Thats aliases meaning other words for it
still doesnt works
Error?
Are u in a vc?
Did u install it properly?
- yes
- yes
is the command even being invoked
pip install discord.py[voice] - i installed it
idk
add a print statement to it
before
huh?
and after
ok
after the :
lol
what if a1 includes spaces, a2 includes spaces, etc
itll work
then it'll use a2
indents
but doesnt join
what?
ooof
Like if you do .test 1 2 3 it'll use arg1, arg2, arg3 but if you do.test 123 it'll only use arg1
Make that parameter key word
yes thats my problem here, assuming I need a command that has two arguments, each argument with spaces
like, can we do $command "first argument" "second Argument"
yes
so what can i do?
uh arg1:str and arg2:str then try to do .test "Arg 1" "Arg 2
Is there an error tho?
no
lemme try that
do i need to do smth here?
try it ig
no
you can do this there
so what can i do for the join command to work
is there really no error
you dont need the presence intents for the bot to join voice channels
no errors?
no
do you have an error handler?
a what?
error handling
Meaning something to handle your errors
on_command_error event
Error Comes => Error Handler Helps With The Error
yes
try to make an else statement and then make the bot send the error?
the error handler is eating up all of the errors
so the console doesnt send it?
on the top/bottom?
oooo, ok
!d discord.ext.commands.CheckFailure
do i delete it?
exception discord.ext.commands.CheckFailure(message=None, *args)```
Exception raised when the predicates in [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks") have failed.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")
look at this message
yea
I just have an error handler that sends all the errors
bru
what?
do pip install discord.py[voice]
install PyNaCl
is it easy?
i installed iyy
what
i have
u did?
i think
i dont see 🧐
ok
hm
np
guys how do i use if command in discord.py?
now I'm trying but the bot doesn't give an answer if I try to use "if"
Meaning?
give more context pls
eg
i mean if the question that is sent
and a right answer is given, I want to give it the "if" function so if that question gets the right answer the bot sends the message that they are correct
hey guys do you thikn this is legitemate I am tryna make a rickroll command https://media.discordapp.net/attachments/888038236889415731/890942971367796746/unknown.png
is this in DMs?
yes
are those allowed
help :(
what?
I mean ```py
async def test(ctx, arg1):
if arg1 == 'hi':
await ctx.send('arg1 is hi')
else:
await ctx.send('arg1 isnt hi')
Nothing lol
lemme try
answerlist = ["answer1", "answer2"...]
@client.command()
async def guess(ctx, answer):
for i in answerlist:
if answer == i:
await ctx.send("correct")
else:
await ctx.send("wrong")
yes seems legitimate but from my experience nobody is gonna click a random link because they're lazy 👀
lol
@river kindle ^^
if i see that in my dms, im blocking the bot
tysm now i need to go i try later
like no way im trusting links like that
you're welcome
its for a rickroll command
you asked the question asked 10 days ago
What means - Discord Shards ?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
^
you could just copy the link and using your smart python brain check the websites code
false
he did?
i asked for a suggest command 10 days ago
no i say that @jagged wigeon asked the question i asked 10 days ago
Sharding is the method by which a bot's code is "split" into multiple instances of itself. When a bot is sharded, each shard handles only a certain percentage of all the guilds the bot is on. You do not need to worry about sharding until your bot hits around 2,400 guilds. ...
you could just make your own its not that hard
o
Thanks a lot!
ok
unless your making it multi server then yes it would be hard
^
multi server isnt hard either
new pfp i see
yes
it's command_error
lazy error handler
true but for a person thats not smart it kinda is
sorry I use the async branch is it command_error and not on_command_error?
Does it work?
it works for me
o ok
I meant u used on_message_error
why are you using the async branch
every event uses on_ in the start on the async branch I think
idk I'm more into it and I don't have time to learn the rewrite one
so you dont have intents
Well thats a first, II aint seen async in yoinks. Not likely it doenst support anything new you kinda want / need going forward. Plus its nicer imo, feels better with oop
on_
I made this command that changes the color everytim
@commands.command()
async def ping(self, ctx):
a = "012356789abcdef"
p = ""
for i in range(6):
p += random.choice(a)
print(p)
color = turninto(f"0x{p}")
msg = await ctx.send(
embed = discord.Embed(
title=":hourglass: Latency/Ping",
description=f"Ping\n\n`{int(self.client.latency*1000)}ms`\n`{str(self.client.latency)[:-10]}s`",
color=color
)
)
for e in range(50):
color = 0x0
p = ""
for i in range(6):
p += random.choice(a)
color = turninto(f"0x{p}")
await msg.edit(
embed = discord.Embed(
title=":hourglass: Latency/Ping",
description=f"Ping\n\n`{int(self.client.latency*1000)}ms`\n`{str(self.client.latency)[:-10]}s`",
color=color
)
)
I meant oops for deleting the orhter message lol
not this one, I'm just showcasing my rainbot command
:P
role_made_on = role.created_at.timestamp()
role_made_on_1 = int(role_made_on)
--
Created on: f"<t:{role_made_on_1}>"
```Any idea why this actually returns the incorrect time of the role being made for my region? I did the same thing with member.created and it works fine.
I haven't worked with timestamps yet I'll use it soon for log files
nice api spam
I get an error but the discord.py module prevents the error from happening until I use mulithreading to spam.
Its kinda fun using it
!voiceverify
idk
it just looks cool I think
I don't do programming for illegal things I just use it to enjoy my crappy life :P
it's not a good or smart or thing to do
I know.
It changes to a random color every discord tick
blanket you have any idea on how to help?
idea for what
this
cuz its defaults to UTC
doesn't discord format adjust to your region?
thats just a standard
I use GMT time
no?
wait
oh you're talking about the discord timetsmap
yeah
well idk, havent used them
I use datetime module
I think you can use a timestamp object of some sort to get the correct timestamp from the timestamp object
!warn 887672943268757585 We are not going to help you with projects that violate rule 5. Please don't ask for help with this or other rule 5 violations again.
:incoming_envelope: :ok_hand: applied warning to @ionic path.
sorry
I love how @unkempt canyon use the ok hand as if the warn was sent and recieved by that hand
@slate swan I found this on the discord developer portal documentations
I think you can use this
!d discord.Role.created_at.timestamp
wow not there
.timestamp() returns what you showed
hm
Hey, how can I check if a message sent contains an image?
@commands.Cog.listener()
async def on_message(self, ctx):
isbot = ctx.author.bot
if isbot == False:
messagecontent = ctx.content
messageattachments = ctx.attachments
if not messagecontent:
await ctx.channel.send("Please attach some text.")
else:
await ctx.channel.send(f"Message content: {messagecontent}")
if not messageattachments:
await ctx.channel.send("Please attach an image.")
else:
await ctx.channel.send(f"Message content: {messageattachments}")
``` This is what I ended up with
it's a timestamp?
yeah e.g <t:242427624>
yes that
created_at.timestamp returns a unix code which you can convert to a timestamp
yes, you did
the time it gives isn't correct though
it isn't?
I dont know what is wrong
hm
deleted?
@hasty iron
Read rule 6 then, if it's false, contact the staff
@novel apex
ok
!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.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
remove the invite link in the code then?
not it
my code has a role name
so it deleted it
This is my code
from discord import client
from discord.ext import commands
client = discord.Client()
@client.event
async def on_ready():
await client.change_presence(status=discord.Status.do_not_disturb)
print("BOT IS READY")
@client.event
async def on_raw_reaction_add(payload):
message_id = payload.message_id
# print(message_id)
if message_id == 890452739048497222:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
# print(guild_id)
# print(guild)
# print(payload.emoji.name)
if payload.emoji.name == ":white_check_mark:":
role = discord.utils.get(guild.roles, name = role_name) # role_name is defined just that i can not paste it here as deletes it
# print(role)
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
print(member)
if member is not None:
await member.add_roles(role)
print("Verified")
else:
print("Member not found")
else:
print("Role not found")
client.run(tocken)```
@hasty iron
whats the problem ?
where exactly
end of the code
print(member)```
member is always None
everything else works
I was trying to create a hosting script to host multiple bots online and i have the script done its running nicely but it just logs 1 bot & stops loggin anyone help ?
do intents = discord.Intents().all() and then client = discord.Client(intents=intents) or client = commands.Bot(command_prefix='', intents=intents) at the begining of your code it should work
ok let me try
Here's the script :
from discord.ext import commands
tokenfile = open("lines.txt", "r")
#tokens = tokenfile.read()
def Hosting(token):
client = commands.Bot("exor!")
@client.event
async def on_ready():
print(f"Connected : {client.user}")
client.run(token)
for x in tokenfile:
Hosting(x)
iirc this is not possible, 🔽 do what blanket said
and then at the end loop.run_forever so it runs the tasks
do the last one
Umm
intents=intents
Ok
Oh forgot
ok
trying
just copy past the code at the beginning
tell
Guys, is there a way to get the hexcode of the top-most role of the message author
commands.Bot is a better option
1s
hexcode?
you mean the color hex of the top most role?
oh you mean color?
ctx.author.top_role.color maybe?
yes
@upbeat otter
i need the hex code of the color, i can get the color easily
first set the proper permission first
meaning?
so it is client = discord.Bot(intents)
wait
what do you mean?
search what is hexcode ......
It tells you in the error.
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/
and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Go to the developer's portal and enable intents.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
This? #ffab85
from discord.ext import commands
client = commands.Bot(command_prefix="your command prefix here", intents=discord.Intents.all())
ok
yes
thats what i said tho?
yes but you have to do color=0xffab85 for color
where do I enable it?
o
do str(ctx.author.top_role.color)
discord application portal
it returns the hex code
i said that -_-
oh lol, i thought that was for getting the color 🥲
ctx.author.top_role.color returns Color
which one? presence intents? or server members?
casting str on it returns the hex
def __str__(self) -> str:
return f'#{self.value:0>6x}'
.. describe:: str(x)
Returns the hex format for the colour.
presence intents
isnt the color the hexocde?
@boreal ravine im really sorry 😭
let me try
ok done
ok.
run the code and tell me
changed that now, and limited it to no presence and no members intent
i had to enable both for it to work
How to disable button after clicking it ? btw using discord_buttons_plugin and I know that discord has a build in button event handler but, well its just my preference
ok does it work y/n
testing
ok
button.disabled = True
worked ?
nope
it works now, i just rewrote it in another project
already tried that didn't work
here is the code: ```py
@Buttons.click
async def y (ctx):
send=discord.Embed(color=0x51ed87)
send.add_field(name="Action Confirmed", value="Report successfully sent.")
await ctx.message.edit(embed=send)
@Buttons.click
async def n (ctx):
discard=discord.Embed(color=0xed4245)
discard.add_field(name="Action Failed", value="Report discarded")
await ctx.message.edit(embed=discard)```
client.loop.create_task(client.start(token, bot=False))
client.loop.run_forever()
Maybe i did it wrong cuz i aint good at py imma js nab , but it still doesn't loops any idea ?
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Did u update the action row after that?
its a selfbot
Ik it is
self-bots are against ToS no matter what you do
Cuz i was curious to try something new
ok then try it but you're getting no help here
yes
Um ok i won't do but any ideas with the normal bots
what are self bots ? @hasty iron
i wont help you its too late
you asked about a self-bot and now you switched your same question to normal bots
Sorry bro, never used that module
its fine
is json good for making levelling bot?
no
im using aiosqlite
is it possible to use aiosqlite with replit?
dunno
why do people use replit? Like just use an ide on your own machine
why on earth would you want this
create_role() takes 1 positional argument but 2 were given
role = await ctx.guild.create_role(name)
I only have 1 argument though?
i will send the current level and exp in a channel of discord. the message will be edited every time the user level up. there will be a seperate message for every user. when the user will type >level, it will find the message for the user from the channel and get his/her level? how about this/
it takes only kwargs i think
sounds awful
!d discord.Guild.create_role
await create_role(*, name=..., permissions=..., color=..., colour=..., hoist=..., mentionable=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") for the guild.
All fields are optional.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to do this.
Changed in version 1.6: Can now pass `int` to `colour` keyword-only parameter.
ik
self gets implicitly passed in, thats why it says 2
any db to use in replit?
practically, I mean
so what should I put instead?
what is the best db to use in replit?
also i don't want it to charge me money after going link 2 mb
your best solution rn is to not use replit
then how will i host my bot?
and where?
self host it, buy a vps or a raspberry
so i have to "buy"?
yes
hmmmm
why
replit uses virtual env
if I buy hacker plan can I use replit..?
replit is not for bot hosting
its not a host
using uptime robot
thats not a host either
uptime robot is not a host
and the replit web viewer
its a thing that pings a website every some minutes
that isnt a host either
forcefully
isnt https://glitch.com/ the same tho
still not a host
bruh glitch
it is really a glitch
im using vultr and it works perfectly fine
edit: its for websites
whats that
vps
hm
Hello! How to localize discord bot using gettext?
any free wps?
no
ok i'll will buy raspberry
unless you get the aws vps which is only 1 year free
!d discord.ext.commands.on_emoji_create
No documentation found for the requested symbol.
doesnt exist
sounds awful what on earth will i do after that freaking 1 year?
pay?
will cost more than a vps
^
nah i am gonna buy raspberry now
stop pls @slate swan
stop it
@ocean leaf will u help
hm
make another acc and get it again
wdym by on emoji create?
OMG SO good idea
@boreal ravine anti nuke bot
what
duh me smart lol
@boreal ravine i need on emoji create for anti raid bot
but if they get to know about this, they will kill me
whats the event?
!d discord.on_guild_emojis_update
discord.on_guild_emojis_update(guild, before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") adds or removes [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
This requires [`Intents.emojis_and_stickers`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.emojis_and_stickers "discord.Intents.emojis_and_stickers") to be enabled.
there is this
who?
this is update
You do realize a raspberry pi is more expensive in the end rather then renting a vps???
Called when a Guild adds or removes Emoji.
@boreal ravine hm
ok
i'll folllow @slate swan
That won't work, most trials require credit card info to identify
idk XD
thats why ppl invented credit card stealing
Commit a federal crime to get a free vps for one year
Very smart
lmao yes
@bot.event
async def on_raw_reaction_add(payload, *, name):
message_id = rct_msg.id
if message_id == payload.message_id:
member = payload.member
guild = member.guild
emoji = payload.emoji.name
if emoji == '👍':
member_id = member.id
member_id = str(member_id)
registered = reg_user.append(member_id)
user = ctx.message.author
role = await ctx.guild.create_role(name=name)
await user.add_roles(role)
print('Role created')```
I meant to reply to your message but no it isn't smart I was joking
how do i make an alt detector command :o?
you cant really "alt detect" you'll just have to guess
the problem is that it is @bot.event , so I'm trying to put the name as a fixed name such as 'role', and assign that role when the user reacts to the message
i would check on_member_join and make em go to a website then get their ip
if another member joins the guild with the same ip ban em
Your best bet is to check for young accounts
yeah but u get me, if the acc is younger than 30 days
ban
check Member.created_at
this?
returns a datetime.datetime obj
??
Wps???
i can;t find it
LOL
yes i need a wps
It's VPS
i would need a code
no
😂
:loading:
andy can you try making slash commands over http and see if it works for you
f
epic fail
discord just refuses to send the message
I'm at work ill have to make my own implementation on break or after work
ok
any wps u know?
I already have an idea of what to do though
pls gimme link
@ocean leaf you do realize we are trying to help you but you're just not listening?
Could take up to
and still ddidnt work
gcp?
discord
gcp is still cloud
counts as a vps to me
if i do it through the endpoint it works ok
Do you need to give it an interaction token or smthg??
will mySQL work with it?
Nvm that won't be the problwm
help please
Its a 200 status
¯\_(ツ)_/¯
so i can fix it but its cheesy
i can have a respond function
i tried it earlier
but somehow the response doesnt get sent
if i do it
I don't have any coding problem but something else related to discord bots can I ask?
Is the cheesy way processing commands then manually posting to the reply endpoint??
the cheesy way is calling the reply endpoint
the docs said use it if you're using the gateway
but eh
i can setup a quick commands system
.
go ahead
Can you send the docs with the HTTP return stuff
Actually my bot uses the name and pfp from some anime and I am afraid it it's some copyright violation. So can you tell me if it is?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
nah that dont matter for top.gg
Alright ill have a look later
Atleast thanks I was using the name mitsuha from Your Name. Now I'll post it tomorrow
Ty
How to localize discord bot using gettext? Help please
doesnt seem like it
How i can do - if player add emoji to this message bot editing message for example Test
!d discord.Client.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
there is an example for reactions
hm
okay so dpy2 is rly difficult
how do i create a menu that is made after using a command?
help please
it adds options based on the args the author provides
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
guys, I don't want to put the value field in an embed, what do i do?
info.add_field(name=f"NAME: {name}", inline=False)
you were using them the other day
put a zero width space
wasnt that a nested class
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1632499096:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
can u give me an example please 🥲
that was my first time using a menu lol
you still subclassed ui.View and ui.Select
oh
put this U+200B inside a string
i see, lemme refer to it then
ohh, thenx
like this?
info.add_field(name=f"NAME: {name}", value="U+200B", inline=False)
yes
so Select was the discord.ui.select class
SeectView was the discord.view class which added the menu into the view
is that what youre talking about? the second class which added the menu to the view
Hey, Python bot aka @unkempt canyon seems interesting.
Is it possible to get this bot in my server??
So that My friends can use it
It's a private bot unfortunately
That's not true
No
But it's open source
!source
I mean, yes
slowmode
You can host it yourself with the correct config etc., but there isn't an actual invite link if that's what you're after @slate swan
this displays the value too
info.add_field(name=f"NAME: {name}", value="U+200B", inline=False)
Do any of the bots here use ui.select yet?
Ok
Not for now
hmm
If u r talking about PyDis bots ^^^
yes
how do i set the value of value field in an embed to None 🥲
how do i add options into a menu based on the args a user provides? i thought the class has to be outside the cog class... so how is it possible to access the users args in that case?
i told you
subclass and overload the init to take arguments
pass those arguments in and use them
value="\u2800"
ohh, thanx
for a command? yea override cog_check in your cog class
Can you explain a bit more?
or if you could tell where I would find it in the docs I can read that
!d discord.ext.commands.Cog.cog_check
cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.
This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
just override this method in your cog class and return True/False like a regular check
Ok thanks 👍
How would I make a bot recognize when a message has a certain keyword and then have it react to that message (with a custom emoji but I have the part figured out)?
I tried
@bot.event
async def on_message(message):
if 'key' in message.content:
emoji = '<:emojiname:1234'>
await message.add_reaction(emoji)
must be emoji = ':emojiname:1234'
Except message isnt working and when I put intents.messages = true it stopped everything from working
ooof discord markdown
# so its something like this
emoji = "<:emojiname:emojiid>"```
you had your > outside the string which may have caused an error
Oh yeah
Thanks
Now it stops recognizing commands after reacting to the keyword and doesnt give any error but I'll come back later, I'm gonna stop working on this for a few hours
bot.process_command('message')
use this coroutine at the last of your on_message event
I will try that when I get back to it. The ('message') is exactly that? Or i replace it with the keyword?
nah , just add py await bot.process_command(message) at the end of your on_message event
message is not supposed to be a string
oh ye
@bot.command()
async def config_muterole(ctx):
try:
guild = ctx.guild
permissions = discord.Permissions()
await guild.create_role(name='muted')
role = discord.utils.get(guild.roles,name="muted")
for guild in bot.guilds:
for channel in guild.channels:
if str(channel.type) == 'text':
await channel.set_permissions(role, send_messages = False)
except Exception as e:
embedVar = discord.Embed(title="Error;", color=0x2C5ED1)
embedVar.add_field(name="** **", value=str(traceback.format_exc()), inline=False)
embed = await ctx.send(embed=embedVar)
The error I'm getting here is:
404 Not Found: unknown overwrite
Can't figure out what's wrong, can anyone help?
wth
ratelimits exist......?
@bot.event
async def on_raw_reaction_remove(payload):
message_id = payload.message_id
if message_id == 891002171397636137:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id , bot.guilds)
if payload.emoji.name == 'white_check_mark':
print("yay")
else:
role = discord.utils.get(guild.roles,name = 'Verified')
if role is not None:
member = discord.utils.find(lambda m : m.id == payload.member.id , guild.members)
if member is not None:
await member.remove_roles(role)
print("done")
else:
print("member not found")
else:
print("role not found")```
I have this class outside of my cog
how do I use it with variables provided on command inside the cog?```py
class CustomMenu(discord.ui.Select):
def init(self):
super().init(
custom_id="CustomMenu",
placeholder="Select options"
)
so do I just put on an asyncio.sleep() before the command or what
I'm gonna determine the max and min values and also the placeholder based on the data i get from the command
no do not do that
Alright thanks
i use this for remove reaction role but
Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 84, in on_raw_reaction_remove
member = discord.utils.find(lambda m : m.id == payload.member.id , guild.members)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/utils.py", line 225, in find
if predicate(element):
File "main.py", line 84, in <lambda>
member = discord.utils.find(lambda m : m.id == payload.member.id , guild.members)
AttributeError: 'NoneType' object has no attribute 'id'```
what i was saying is that your bot will be ratelimited
member is None
there is no payload.member afaik
Is that what the error is about
ok
no
oh nvm there is
I have this class outside of my cog
how do I use it with variables provided on command inside the cog?```py
class CustomMenu(discord.ui.Select):
def init(self):
super().init(
custom_id="CustomMenu",
placeholder="Select options"
)
I'm gonna determine the max and min values and also the placeholder based on the data i get from the command
I'm not too worried about ratelimits, I just wanna know what my error is about lol
Im trying to make a bot for a game I put called madfut 21. I want people to be able to type .buy (player name) and then it sends it to a channel only I can see. How do I do this?
get_channel(id, /)```
Returns a channel or thread with the given ID.
your bot can be terminated
and then channel.send
not worried about that...?
simply add those params in the View object that you're gonna add the CustomMenu to, as well as add those params to your CustomMenu, then pass those params that you get from your View to your CustomMenu
setting channel permissions has high ratelimits, and you want to change all text channels for all guilds the bot is in
and in your CustomMenu you should have some func that fills in the options
as well as set the placeholder and everything else
class CustomMenuView(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(CustomMenu())
``````py
@commands.command()
async def select(self, ctx, *args):
view = CustomMenuView()
view.append_options(...)
```is that what you mean?
as i said, just add the arguments into the init
e.g:
class MyMenu(discord.ui.Select):
def __init__(self, placeholder, min_vals, max_vals, options):
super().__init__(placeholder=placeholder, min_values=min_vals, max_values=max_val)
self.options = options
self.fill_options()
def fill_options(self):
for option in options: # Make sure that ``options`` is a list
self.add_option(label='...')
class View(discord.ui.View):
def __init__(self, placeholder, min_vals, max_vals, options):
super().__init__()
self.add_item(MyMenu(placeholder, min_vals, max_vals, options))
# From here you do however you like
def fill_options(self):
for option in options: # Make sure that ``options`` is a list
self.add_option(label='...')
```What's label over here?
SelectOption.label?
discord.errors.ClientException: Callback for beg command is missing "ctx" parameter.
I get this error In one of my cogs,
Online I see I have to use self, ctx. But I never had to do that to make my commands work. Why do I get this error?
What does this error mean*
the option's name
error means exactly what it means
your command is missing the ctx argument
But like, I have the ctx argument...
then you dont have self
But I never have to use self anywhere In a cog for my commands to work. And while using self I dont get error or output
a cog is a class, self is a required param
But why Is It required as without It most commands work too. And my vscode doesnt output error or output when using self
for every method inside your class (cog)
because all your commands would raise errors
imagine we have async def command(ctx, arg)
But like- they dont
inside a cog
self would be ctx and arg would be ctx
^
how do i make a discord bot embed something in a channel
hmmmm
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
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/master/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.
Yeaahh but the problem Is with self my commands dont work
And It doesnt give me an error
Hello, I found an option selection command from YouTube and the intreaction gives an error. What should I do?
how i make it send in the channel, rn the bot is typing the words "True" and i do not have that anywhere in my code
are you sure they're inside a cog
🤔 whats the part that comes under the command
Yeh
send the cog where you supposedly dont have self
await channel.send(embed=embed) # embed must be an embed object
dont i need ctx?
ctx.channel.send?
if u plan on doing ctx then do await ctx.send(embed=embed)
Hey @rain bolt!
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:
Yeah Its template code, but Im helping someone else with it
fill_options is supposed to be just like any other function?
hmmmm
dude why is it sending that
it's really just so it looks nicer in my opinion
that is literally not in my code
super().__init__(placeholder=placeholder, min_values=min_vals, max_values=max_val) and are these the variables for it?
embed.set_author(name="Point")
embed.timestamp = datetime.datetime.utcnow()
await ctx.send(embed == embed)```
then you defo have your bot sending True or maybe you are checking for an equivalent between 2 things which returns True idk
yes, that's what's gonna put your placeholder, min values and max values
== is for comparision
oh whoops
= is for assignment
ah, i see
Hello, I found an option selection command from YouTube and the intreaction gives an error. What should I do?
import it
another question,
i deleted all my webhooks, yet its still sending one?
from discord_components import *
check if multiple instances of the bot are running
if you're on windows check task manager for python instances
LMFAO im so dumb
ty ty ty
Are you with me
?
Why If I use self, ctx in an cog. The hole command loses his function?
i dont know discord_components, gimme a sec ill look at source code
is there a way where i can say "click here" and it will open up the dms with the bot
so i dont have to right click to dm the bot
why is there labels here? i thought its supposed to be included in the options list which is for discord.SelectOptions
as i said, labels represent the name of your select option
there is no InteractionType in discord_components, type defaults to 4 which is the value for CHANNEL_MESSAGE_WITH_SOURCE so just remove that line
yes, so options=[discord.SelectOption(label="Hello"), discord.SelectOption(label="Bye")]
isnt it?
if you want to know the valid integers you can pass in see https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-interaction-callback-type
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
perhaps, never used it that way
ok
how do i add a custom emoji if i wanna react to a message?
read the For emojis.. part
I did what you said and it worked, but unfortunately I got this error
im having sum trouble
@bot.event
async def on_message(message):
if bot.user.mentioned_in(message):
emoji = ''"
await message.add_reaction(emoji) its not working if i put the emoji thingy
emoji = ''" doesnt look like a valid emoji to me, looks like a syntax error
.
pretty obvious what you should do
you could have a jump url to the bot dms maybe?
yeah thats what i want
but how i do that
hyperlink it
ik whats the URL
not really, im new to python, thats why im askin :/
I did when player add emoji message edit to test and i don't know why embed there is it not is only test
uh dk if it would work but https://discord.com/channels/@me/<botid>
ok ty
put in the right emoji?
it works for me, but on my other account that has no roles or anything it says "you dont have access to this link"
@bot.event
async def on_message(message):
if bot.user.mentioned_in(message):
emoji = ':W_:'
await message.add_reaction(emoji)
but it sends this
well idk
is it animated
no sir
ok so its not adding it to the message right?
nope
does the bot have access to it?
yes
Ignoring exception in on_message
I have another problem - how i can do 2 emoji and if player add one of two get another answer
because now it work for 🥳 emoji
only for this one
do the same thing for other emoji
just a new function?
Is it possible to timestamp my bots creation date in it's status, like <t:1625014920:R> <t:{int(self.bot.created_at.timestamp())}:R>
okay thanks
How i can do it?
which status
owo nvm
yea created_at and then get the timestamp of it and then turn it into an epoch time
status doesn't really support markdown, but about me do, you can set them at the developer portal though for about me
okay thanks all
i think bots cant have custom statuses
okay
so in the command its simply gonna be ```py
async def selecct(self, ctx):
placeholder="something"
max_val=0
min_val=2
options=[discord.SelectOption(label="something")]
MyMenu().fill_options(placeholder=placeholder, max_values=max_val, min_values=min_val)
view=View()
await ctx.send(".", view=View)
@slate swan wow your the stella on the help command? O-o
"stella on the help command" 😂
i didnt say custom statuses, i said about me
gg getting a tag on rdanny I guess
yes
💀
yeah that should work
actually no wait where are you passing your options
also why do you have your max values 0 and min values 2??
options=[discord.SelectOption(label="something")]
MyMenu().fill_options(placeholder=placeholder, max_values=max_val, min_values=min_val)
```shouldnt this work?
it was supposed to be the opposite, sry
no
if you're using the fill_options i gave you then that wouldn't work
async def selecct(self, ctx):
placeholder="something"
max_val=2
min_val=0
options=[discord.SelectOption(label="something")]
view=View(placeholder, min_vals, max_vals, options)
await ctx.send(".", view=View)
that will work
yw
@bot.event
async def on_raw_reaction_add(payload):
msg_id = payload.message_id
with open("rr.json","r") as f:
self_roles = json.load(f)
if payload.member.bot:
return
if str(msg_id) in self_roles:
emojis = []
roles = []
for emoji in self_roles[str(msg_id)]["emojis"]:
emojis.append(emoji)
for role in self_roles[str(msg_id)]["roles"]:
roles.append(role)
guild = bot.get_guild(payload.guild_id)
for i in range(len(emojis)):
choosed_emoji = str(payload.emoji)
if choosed_emoji == emojis[i]:
selected_role = roles[i]
role = discord.utils.get(guild.roles,name=selected_role)
await payload.member.add_roles(role)
await payload.member.send(f"You got {selected_role} Role")```
Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 100, in on_raw_reaction_add
await payload.member.add_roles(role)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/member.py", line 777, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'```
why?
what do you think?
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username} : {user_message} ({channel})')
await client.process_commands(message)
@client.command()
async def help(ctx):
embedVar = discord.Embed(title=f"✦Peachy Bot✦\n Help requested by {username}", description="This is a few commands you can use :", color=0x00ff00)
Ignoring exception in command help:
Traceback (most recent call last):
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Modarresan\Desktop\Peachy Bot\Peachy.py", line 45, in help
embedVar = discord.Embed(title=f"✦Peachy Bot✦\n Help requested by {username}", description="This is a few commands you can use :", color=0x00ff00)
NameError: name 'message' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined
nvm
it keeps giving this error when i use .help
add py await ctx.send(embed=embed)
show code so we can help you…
already have it
oh im blind
where have you defined what username and everything else is
actually the embed is ok
just a sec
btw message.channel.name is already str
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username} : {user_message} ({channel})')
await client.process_commands(message)
that obviously will error
oh
why are u doing it inside an event when ur doing a command
ur supposed to do it inside the command
¯_(ツ)_/¯
before
anyway thanks
np
why not
Traceback (most recent call last):
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Modarresan\Desktop\Peachy Bot\Peachy.py", line 45, in help
username = str(message.author).split('#')[0]
NameError: name 'message' is not defined
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Modarresan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined
now it gives this error