#discord-bots
1 messages ยท Page 601 of 1
oh
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [โ@everyone](mailto:'%40everyone)โ role.
These roles are sorted by their position in the role hierarchy.
@near sail Do you know where I can find documentation on buttons
Buttons are on discord.py 2.0
Yeah
Yeah well I was on there
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
tyvm
Now that discord.py is gone, which Discord API wrapper should I use in Python?
what do u mean by gone?
It's not gone, you can still use it perfectly fine
It just won't get updates for new features
And there are multiple forks or completely different libraries available I guess, I wouldn't recommend to use a fork though.
๐ฆ
disnake ๐
hello everyone, does anyone know a good maintained fork of discord.py?
oh nevermind
someone else asked
How i can easily check if a text channel given by input from a command is a text channel?
I wanted to ask if anyone is interested to learn hikari-lightbulb together..this way we can solve each other's doubts and learn more about developing discord bots...
i just figured out how to make a slash command using the discord_slash module
dm me if you need a basic slash command example
will stop answering within like 5 mins
someone?
You can just share it here, right...?
genius alr
steps to make a dumba freaking slash commands
- go to discord.com/developers go to your bot go to oauth2 kick your bot from the server and then in the bot scopes select
botandapplication.commandsand then reauthorize it back into the server - do
pip3 install discord_slashorpip install discord_slash
- go into your bot code and slap
import discord_slashandfrom discord_slash import SlashCommand
pin this
hikari
uhm you know that there are a fork named disnake which is not related to discord.py and let you create slash commands, right?
well i use discord's py module mainly
hikari
isinstance(channel_arg,guild.TextChannel)
returns a boolean
Ikr
btw is it ok If I post this message once in an hour or it will count as spam ๐ค
why Hikari?
- go for a cycle and do
@slash.slash(name='name', description='description here')
below that piece of sh- doasync def name(ctx):
below that crap indent your damn code and then just doawait ctx.send('your mom')
it's maintained and easy to learn
I think Nextcord looks nice
is that a fork?
yep a discord.py fork
plus it has framework 'lightbulb' which is very similar to discord.py
I'd recommend not using forks
Hikari is better because it's a separate library
and not a d.py fork
ye thats the steps you need to make a slash command
tbh lightbulb v2 is very similar to it syntax wise
if its similar who cares :trol:
Hikari looks nice, because of the static typing
thanks
you know what
nextcord is easier for me as i've made a discord.py bot before, but I think i'll jump right into hikari just for that static typing
lol everyone has different opinion so np
speaking of static typing, how in the world do you get a bot to do typing for how much time you want and then send the message
but isnt depreciated
another big reason for u to switch?
ctx.typing()
ye but how to customize how much time til send
@bot.command()
async def longCommand(ctx):
async with ctx.typing():
await sleep(10)
await ctx.send("Done!")
just sleep
freaking jenius
use time.sleep i see i see
@slate swan i got an error ๐
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: object NoneType can't be used in
'await' expression```
`
oh wait
i see whats wrong srry you dont use await i think
How to create a Task inside a cog?
use asyncio.sleep() instead
the command is gonna block all the other commands if you don't lol
hmm what about time.sleep
you can if it supports async
bot.loop.create_task()?
Hi.
I'm making a discord bot, and I want to know if a bot has the higher role than a specified member.
I see something like discord.User.top_role but I don't know how to use it. Anyone can help? Thank you!
get the member instance > use top_role attribute on it
you get the Member object then compare it like if guild.me.top_role > Member.top_role:
why user tf
Oh thanks
dont come back and ask how to get the member object kthx
Guys, how to make the author the correct condition if the id is in this collection, well, there I use this check
guys I need to use a converter but i don't have a context, what can I do?
you're using dpy 2.0 right?
what/which converter
oh so you use discord-components for button , in the check right?
No, dislash
yea so inter.author.id would be the thing
but I have now to send an img from an url
its correct
can u explain why u cant use it?
Converters requires a context object as first argument
i need the channel into a tasks loop
Ah
so i don't have a context
can't u just do ```py
async def ...(channel: discord.TextChannel):
nope, it is not a command, is a tasks loop
you can make a custom context
I want to make a blacklist for the reporting system, using the command I add a person to the database collection and in this check I want to find out if the author's ID is in the database
never said it was a command
By the way i have to send an image from a url (just a send message, not embed), how I do that?
But the check that does not work for me, for some reason it is not taken into account and allows me to create a report, although my ID is in the database
just send the url
discord will embed it
i didn't wish to show the url :L
ahh so , collmember.find_one returns a single user which may or may not be the user you want
maybe try getting all the members and use it
i dont use mongodb , so exactly dont remember it , its something like find_all if im not wrong
AttributeError: 'NoneType' object has no attribute 'get_member'
im getting this error, code is
@commands.Cog.listener()
async def on_message(self, message):
x = message.guild.get_member(118470023181369344) or await message.guild.fetch_member(118470023181369344)
if x in message.mentions:
em = discord.Embed(description = f"{message.content}",color = discord.Color.blue())
em.set_author(name=message.author, icon_url=message.author.avatar_url)
em.set_footer(text= message.created_at)
if message.attachments:
em.set_image(url = message.attachments[0].url)
await message.channel.send(embed = em)
i cant see what im missin
well , it wont work in your case ig since it needs a message object already
message.guild is None , aka the command was used in dms
well, i think I can find a way
Like save one message into the database from that guild id
you just need a text channel object right?
that's weird, the event isnt being triggered in dms
well thats what the error says , i dont see any other reason for message.guild to be none
have your turned off guild intents?
I did like this, but it still doesn't work
Either it's in dms where .guild is None, or you're missing intents
yup
nope, all intents are on, but ye i removed the line where it sends a message to the user and its fine
thanks
can you show what code do you have other than it
which has to be same for all the time right?
it depends on the administrator of that server, they can change it, but it will be saved in the database by the way
So i don't need that the context is the same channel, i just need a context object
you can get the channel from the database tho py async def your_task(): bot.get_channel(<the id you get from db>)
never tried this thingy , lemme check the docs
just use get_channel method
it will give u the channel object
lol can you send the docs?
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
how can I find the number of users connected in the voice channel
!d discord.VoiceChannel.members
property members: List[Member]```
Returns all members that are currently inside this voice channel.
hm
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
@rm.event
async def on_member_join(member):
channel = rm.get_channel(910432929216344105)
embed = i defined embed here
await channel.send(embed=embed)```
it just won't send the welcome embed
no error printed
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Enable the members intent
I enabled it... And now I'm getting
Attribute error : 'NoneType' object has no attribute 'send'
what's rm
is it your bot?
yea
in that case
either you gave a wrong ID
or the bot doesn't see the channel
in get_channel()
umm that id is valid and the bot can see the channel too
send the whole error then
in copy paste
with more traceback...
how i can get my total commands ?
!d discord.ext.commands.Bot.commands
property commands: Set[discord.ext.commands.core.Command[discord.ext.commands.core.CogT, Any, Any]]```
A unique set of commands without aliases that are registered.
mhm
of commands i don't want them
why all_
wait
bot.commands ??
yes
ok :/
well what do you exactly want
just the name?
of the commands
or the description too?
no
my bot show this the len of commands but when i add aliases in any command it add that also in the length
so why do you use .keys
how to get any user's pings ?
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
!d discord.Member.mentioned_in
mentioned_in(message)```
Checks if the member is mentioned in the specified message.
Then?
but other bots show that
You serious right now?
idk what it show
๐
Thatโs not your ping. Thats the bots ping.
!d discord.Client.latency
property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
but it shows different of each user
but it shows different
Smh
Because ping wonโt always be consistent
i also thought that
but when my friend did
it was showing something near 1000
Hmm
:/
ok
!d discord.Client.latency is what they use
property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
how can i make my page system ignore previous messages?
pages = 2
cur_page = 1
#embed stuff
message = await ctx.send(embed=emb)
await message.add_reaction("โ๏ธ")
await message.add_reaction("โถ๏ธ")
def check(reaction, user):
return user == ctx.author and str(reaction.emoji) in ["โ๏ธ", "โถ๏ธ"]
while True:
try:
reaction, user = await self.bot.wait_for("reaction_add", timeout=5 check=check)
if str(reaction.emoji) == "โถ๏ธ" and cur_page != pages:
cur_page += 1
await message.edit(embed=embed1)
await message.remove_reaction(reaction, user)
elif str(reaction.emoji) == "โ๏ธ" and cur_page > 1:
cur_page -= 1
await message.edit(embed=emb)
await message.remove_reaction(reaction, user)
else:
await message.remove_reaction(reaction, user)
except:
pass```
And fast too hehe
XD
Use timeout in wait_for
same story
Code
updated the timeout part too before hand
Weird
still happening?
Wait, it will update the time out everytime u react
i think it has to do with the curpage portion of each if/elif. Whenever i did wait_for's with reactions that was always my issue :/ idk why
so what do you recommend
About What
You really can't do anything...
Sure. But that will also update the time out whenever the person reacts
@bot.command()
async def myMenu(ctx):
totalPages = 2
curpage = 1
embed = discord.Embed(title="Number 1")
emb = discord.Embed(title="Number 2")
msg = await ctx.send(embed = embed)
emojis = ["emoji1", "emoji2"]
for emoji in emojis:
await msg.add_reaction(emoji)
def check(reaction, user):
return user !== user.bot and reaction.message.id == msg.id and str(reaction.emoji) in emojis
while True:
try:
reaction, user = await self.bot.wait_for("reaction_add", check = check, timeout = 60)
if str(reaction.emoji) == "emoji1":
if curpage > totalPages:
await msg.remove_reaction(reaction, user)
elif curpage < totalPages:
await msg.edit(embed = emb)
await msg.remove_reaction(reaction, user)
curpage += 1
............ etc
is how i did it.
not related but use buttons, they're easier to use imo
you still need to use a wait for. i mean they look cleaner, idk about easier though. I also haven't used them since discord_components first came out
No except block
i didn't finish it. Just a starter to explain how i handled the curpage portion
Ah, okay
Is he like asking to ignore previous paginators?
Better is to subclass View
Ye
I mean using a fork, converting to a dpy fork isn't all that hard.
the disnake way ๐
Does he ever break out of his while loop.
Yessssss
||I haven't used dpy or anything python since danny discontinued||
||lmao||
well that's not totally true. I do maintenance on existing bots.
I personally started using dpy in june/july when my school had a 2 month break ๐
nice.
Yeah is it just me or like. Do you ever break out of your while loop. Whatever commands are using that paginator are probably not even executing all the way through because you're in a constant while loop waiting for reactions.
idk how to explain why you put it in a while loop (just woke up here) but its what you are supposed to do...
ahh
so should add a break in the asyncio.timeout portion of the except?
Honestly
Id just add like an โ reaction to the message and when they click that it breaks out
yeah that is what i would usually do and have it delete the message before breaking.
Mhm
property mention: str```
Returns a string that allows you to mention a role.
you access the members roles with member.roles and iterate through that and run role.mention on it to get the "ping"
so yes, yes that
Hmm
[r.mention for r in Member.roles]
I want like this
And join that somewhere ig
this would be what you want then, and just run .join on that list
I am needing code to copy a image from a message
A list of attachments given to a message.
Contains the list of images in a message
Ok thanks I will look at that
Can I get an example of the code?
print(ctx.message.attachments)
ยฏ_(ใ)_/ยฏ
Returns a list of all images
Then use a loop to get each image individually (basic Python loop)
so
we added reaction pages on shop
I know that
not recommended to use on_reaction_add for paginators
or whatever ur doing
!d discord.Client.wait_for usr this
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**...
@normal folio heres the answer
!paste instead of sending a picture
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.
u fix
no men
men i asked u to help not just sit
Because itโs asyncio.TimeoutError
How can I get it to attach the attachment to the mesaage?
Caps matter
do i get hid of it or max it out
anyone here use discordrb?
Anyone know how to use discord buttons as commands?
!d discord.Message.attachments
A list of attachments given to a message.
How to stop local ratelimits?
???
Can I get a line if example code?
No Iโm telling you to go to line 114 in main and fix your caps
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Use the f-strings
.....?
He's sending "ctx.message.attachments" instead of using f-strings correctly
Lol
Why would you even ask it like that anyways
I am using f strings
await ctx.send(f'ctx.message.attachments')```
Tbh if thatโs all heโs putting. He doesnโt even need to f string it. Just pass it in as is.
Pretty sure thereโs automatic string casting.
No you're not, f-strings requires variables to be in {} which you never did
Add your curly brackets.
how do i use that?
example plz
There is an example on the documentation

!d discord.ext.commands.Bot.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**...
See by yourself
Fair warning this probably isnโt gonna give you what you want. Itโll give you a list of reprs.
It just gives a list of Attachment objects
Loop through it as I already said
And use the .url attribute to get the URL of the attachment
Basically what I said. Doing that as is will give him the reprs of each attachment object.
How can I extract just the url from that
Just said above
[i.url for i in Message.attachments]
Make a loop and get the .url attribute
Finding it so hard to learn how to use buttons
all videos are just old packages for d.py 1.0
That returns
['https://cdn.discordapp.com/attachments/798726720181633047/910540678247882822/20211117_092059.jpg']
How can I remove the square brackets and the single quote
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
My brain == null rn. I don't understand it. Could you send a sample?
come on man, this is really really simple :/
dont you see an example in the embed from bot?..
@flint isle
!join is there tho
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
Idk if that's what u got the ss from, but who cares
Exactly from the embed that got already sent and that you sent again for no reason
And as I said
In case you can't filter what information you need to care about
Anyone know how to create commands out of buttons, or where I can find info on buttons
kind of going crazy here 
!seperate
you wanna break a string? use split
!split
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['word1', 'word2', 'word3']
@slate swan So if you get the Role object you can quickly just grab a list of members with said role https://discordpy.readthedocs.io/en/stable/api.html#discord.Role.members
oh so i'd just append their ids to a list ?
Default is space but okay
not sure what to exactly do
You're wanting to add the role to someone?
In that case there's a method to do that
you know how some people leave the server and join back to avoid mutes, i'm trying to it so if they leave while they have the muted rule they'd get it back if they joined

So at least within @unkempt canyon
We end up storing those in a database, and check against it when people join
See if they had any relevant roles/infractions on them to reapply
oh , wasnt aware about that
Sorry, I was lacking in the caffeine department
i'm just trying to do it with one role and its not that big of a server , would a list be a good option ?
its fine no worries
Sort of. The problem is that if the bot goes down, that list does too, so you'd need some sort of persistence
oh right
maybe before the bot goes down it would store that list in a json ?
on_bot_disconnect or something
That's assuming it doesn't crash
I'd recommend just using a little SQLite database
ik how to use databases , but then whats the use of json ?
States
JSON is for - yeah that
states ?
It's typically for data transfer rather than storage
Like getting it back as a response from a web request
i'll go with postgresql
If it's just for one server, that's a bit overkill
SQLite would be more than sufficient
thats why i was intending to use a list
just use sqlite , aiosqlite if you want it to be asynchronus
Then thereโs no persistence
idk how to use sqlite that much either , i've used mysql before
Essentially the same
Cache is flushed every time the program is terminated
oh fair , i'd go with mysql then
It just puts it in a single file rather than connection to a server
they are almost same , bet
aiomysql 
That's the main benefit of SQLite is that it's tiny and doesn't really require much setup at all
^^^^
fair
it uses the same sql query right ?
Yeah. I think the only difference might be how it handles adding variables to the query, but the core SQL itself is the same
almost , other than ? instead of %s
That
oh cool cool
Thanks, I couldn't remember
also uh just for the record how to make a list inside an init method
def __init__(self, bot,muted_people=[],last_user=None):
self.bot = bot
self.last_user = last_user
self.muted_people = muted_people
``` like wise ?
No, that's a bit of a beginner's trap
So if you do that, if you end up using the default value, it'll be the same list for each instance
Rather than a fresh one
Yeah, if you need it consistent across all instances.
But if you're potentially passing in an existing list, then you'd need to do it that way
I think
Difference is.... one sec, writing example
def mah_function(my_list=None):
if my_list is None:
self.my_list = []
else:
self.my_list = my_list
I mean that's a clunky example, but you get the idea
i apply the same logic to the init method ?
thanks hemlock , i really appreciate it
a new list for every instance
!e
def ham(number, spam=[]):
spam.append(number)
print(spam)
ham(5)
ham(6)
@ashen notch :white_check_mark: Your eval job has completed with return code 0.
001 | [5]
002 | [5, 6]
Could be, but it's really dirty
yeah first one looks cleaner
And I think it's an implementation detail, so it shouldn't be relied on
how do i use wait_for cuz i was trying to figure out
@bot.event
async def on_reaction_add(message, reaction, user):
if message.content.startswith(',shop'):
if user != bot.user:
if str(reaction.emoji) == ':arrow_right:':
em2 = discord.Embed(title = "Shop - Others", color = discord.Color.purple())
await reaction.message.edit(embed=em2)
if str(reaction.emoji) == ':arrow_left:':
em = discord.Embed(title = "Shop - Tools", color = discord.Color.purple())
await reaction.message.edit(embed=em))':thumbsup:')```
oh fair , thanks hemlock appreciate it
someone knows how to remove the help command that is on default in a discord bot?
Bot.remove_command("help")
ok thx
Ninja'd
reaction takes only reaction and user as args
if you want the message you may use reaction.message
I think this example might help. Snagged it from the docs:
@client.event
async def on_message(message):
if message.content.startswith('$thumb'):
channel = message.channel
await channel.send('Send me that ๐ reaction, mate')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '๐'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('๐')
else:
await channel.send('๐')
``` https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.wait_for
I think it's what you need?
Not 100% sure, though
@slate swan Just to make sure you're seeing this
!e
Url = ['https://cdn.discordapp.com/attachments/798726720181633047/910540678247882822/20211117_092059.jpg']
Separator = "'"
Print(separator.join(colors))```
nu nu , they are trying to do something when a reaction is added
If the reaction's message starts with ,shop they would proceed
yea , if they use wait_for
but they are using the event decorator
!e
Url = ['https://cdn.discordapp.com/attachments/798726720181633047/910540678247882822/20211117_092059.jpg']
separator = "'"
print(separator.join(Url))```
it would be the same since there is a single entry in the list , what are you really trying to do?
The example I listed is as well
client.get_guild(672453244336734208)``` returns `None`
guild is not in the cache , the bot is not in the guild...
it is
if it is , make sure that you dont have your guild intents off ( its enabled by default tho)
path = "./suggestions.json"
amount_times = 1
data = {}
data[message.author.id]
with open ("./suggestions.json","w") as file:
json.dump(data, file, indent=4)```
may i see your intents
I'm trying to make it so everytime they send a message it opens the "suggestions" json file and adds another number to their ID in the json.
I'm still trying to learn, but basically I wanna do something like:
user_id: 1
user_id: 2
I have discord.Intents.all()
can anyone help me with this?
data[message.author.id] needs a value too , sir
I know a database is easier but still trying to learn.
all intents enabled
So data.[message.author.id] = []?
path = "./suggestions.json"
amount_times = 1
data = {}
data[message.author.id] = []
with open ("./suggestions.json","w") as file:
json.dump(data, file, indent=4)```
and are you sure that the guild id is correct
missing arguement
yes
thnx
I don't get how to add a number then append it by one for the user
How to make it work only on specific command ,shop
yea but , why an empty list
Wdum
in your shop command , use wait_for
as the example hemlock sent
where exactly?
Wdum by empty list
[]
in your command function
what goes in it?
the value you want for the key?...
@bot.event
async def on_reaction_add(reaction, user):
if user != bot.user:
if str(reaction.emoji) == "โก๏ธ":
em2 = discord.Embed(title = "Shop - Others", color = discord.Color.purple())
await reaction.message.edit(embed=em2)
if str(reaction.emoji) == "โฌ
๏ธ":
em = discord.Embed(title = "Shop - Tools", color = discord.Color.purple())
await reaction.message.edit(embed=em)
``` also here is the code
what does your shop command look like?
So whatever I put in it will go into the json?
ofcourse
I'm trying to dump this into json
user_id: <amount of times talked>
that's it
can i send it in dms? cuz i don't want to flood this chat
but idk how
with open('the_json_file.json' , 'w') as file:
data = {}
data[str(message.author.id)] = #number of time the command was used
json.dump(data , file)``` thats how json works
as for the how many times the user talked , you may keep on adding 1 to the value of data[str(message.author.id)] which would be a reading operation first , and then writing it
So what is data = {} doing?
And data[str(message.author.id] is turning the variable data into the users ID?
That makes sense, but then how do you format it how you want.
data = {} is declaring an empty dictionary to be dumped inside the json
how can i fix a missing argument error?
oh
you provide an argument to fix it
But then how could you make the number not fixed?
im new so idk much
as i said , read the json , get the value , add 1 to it
dump the new value
you need to typehint member to discord.Member
So I got it to dump my ID
and , mention someone when use the command
ohhh so i change it from member to discord.Member? alr
nuuu it would be py async def gayrate(ctx , member : discord.Member):
alr alr
it works tysm
wait ill send something to make json more clear
Yeah I need to learn it from the ground up.
I think trying to do it this way won't work.
well , if you use sqlite3 , its much easier
So JSON is the old way?
But JSON is more useable when you don't wanna use a host.
mongodb is quite good, it's non-relational db
json is not meant to be a database
No but you can use it as one lol
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Oh I'm trying to take a output from
await ctx.send(f'{ctx.message.attachments}')```
And remove the `['` and `']` so it's just the link
i see , you can do "\n".join(ctx.message.attachements)
Error
loading embed cog
Ready!
whiskeythefox initiated boop command.
Ignoring exception in command cmd:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "<string>", line 46, in boop
AttributeError: 'Message' object has no attribute 'attachements'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Message' object has no attribute 'attachements'```
The code
```py
@bot.command(name='cmd', description='boop someone', alias=['cmd1','cmd2'])
async def boop(ctx):
print(f'{ctx.author.name} initiated boop command.')
await ctx.send(f'{ctx.message.attachments}')
await ctx.send( "\n".join(ctx.message.attachements))
Url = [i.url for i in ctx.message.attachments]
separator = " ' "
print(separator.join(Url))
print(ctx.message.attachments)```
Ok
I got this error after I fixed spelling
loading embed cog
Ready!
whiskeythefox initiated boop command.
Ignoring exception in command cmd:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "<string>", line 46, in boop
TypeError: sequence item 0: expected str instance, Attachment found
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/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: TypeError: sequence item 0: expected str instance, Attachment found```
eh i see
you would have to iterate thru the attachments frst
list_urls = []
for atchm in ctx.message.attachments:
list_urls.append(atchm.url)
await ctx.send( "\n".join(list_urls))
So
How do I check if the user is in the json?
if data[str(message.author.id)] not in list(data.keys()):```
Like this?
Yes!! It worked
Now I have to find how to make the bot wait for a reaction on a message
@slate swan ^ would you happen to know how to do that?
!d discord.ext.commands.Bot.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โs a much faster and easier way to do this
List comprehension exist. And when he asked the same question earlier I already gave him the code he needed to join.
doesn't respond to reactions
He was literally just waiting for someone to spoonfeed him code on joining an iterable to a string even though we pulled up examples for him.
how to handle multiple reactions in this case?
await form_recebido.add_reaction('๐ฉ')
await form_recebido.add_reaction('โฌ')
await form_recebido.add_reaction('๐ฅ')
def react1(reaction, user):
return str(reaction.emoji) in "๐ฉ"
def react2(reaction, user):
return str(reaction.emoji) in "โฌ"
def react2(reaction, user):
return str(reaction.emoji) in "๐ฅ"
await bot.wait_for("reaction_add", check=react1)
await autor.send('accepted')
await bot.wait_for("reaction_add", check=react2)
await autor.send('to analyze')
await bot.wait_for("reaction_add", check=react3)
await autor.send('denied')
do one wait_for
the check should pass when the reaction is any of those
then you can check which reaction it was with if statements
and, would the "if" look like this?
if reaction.emoji == '๐ฉ':
await autor.send('accepted')
d!client
How do I check if a user has a role outside of cogs? It's in on_message
!dclient
#bot-commands
!d client
oh ye
- get the role object
role = guildObject.get_role(role_id) - check if it's in the person's roles
if role in message.author.roles:
@commands.Cog.listener()
async def on_message(self, message):
if not syst.isMod(self.message, message.author): return ```
Why won't this work? It works in cogs
well a lot of things are different in cogs

the bot don't send the message to user's dm
@commands.Cog.listener() is @botObject.listen()
events/commands outside of cogs don't take self
syst may not be defined
well um
I don't have no information about that
role = guildObject.get_role(892863132299587595)
if role in message.author.roles:```
Doesn't work says guildObject isn't defined
why do you think
you have to replace it with what the name says
a guild object
idk
message.guild probably
hey
got it working ๐ฎ
autor = ctx.author
await form.add_reaction('๐ฉ')
await form.add_reaction('โฌ')
await form.add_reaction('๐ฅ')
def react(reaction, user):
return str(reaction) == '๐ฉ'
def react(reaction, user):
return str(reaction) == 'โฌ'
def react(reaction, user):
return str(reaction) == '๐ฅ'
await bot.wait_for("reaction_add", check=react)
if reaction.emoji == str('๐ฉ'):
await autor.send('txt1')
if reaction.emoji == str('โฌ'):
await autor.send('txt2')
if reaction.emoji == str('๐ฅ'):
await autor.send('txt3')
``` It was like this
nice job @slate swan
well um
no, that's not it
def react(reaction, user):
return str(reaction) == ':green_square:' or str(reaction) == ':green_square:' ...```
one check would make it
with this formula
ok
so redefining a function doesn't do anything
just the last one would be how it's defined
the first 2 are just memory wastes

and I have to correct myself
def react(reaction, user):
return str(reaction.emoji) == ':green_square:' or str(reaction.emoji) == ':green_square:' ...```
if str(reaction.emoji) == '๐ฉ':
can someone help me with this error?
not without code
this is the code i wrote
i was about to send it lol
first of all, while True will block everything else in your code
so i remove it
you should make a task
google it
but the main problem is that get() didn't find the role
ohhhh
in the server i dont have any roles
that might be the problem

lmao
-Computer, find this for me. Hint: it don't exist
-ok
:)
discord.utils.get(ctx.guild.roles, name="everyone")
Is this possible?
!d discord.Guild.default_role
property default_role: discord.role.Role```
Gets the @everyone role that all members have by default.
Hi, is there a way to get the members avatar without the url? Like I don't get a url but a file
in 2.0
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
wdym 2.0? Do I have to update a version or smth?
you might have to
I'm not certain
oh kk i see
because the API reference doesn't explicitly mention it
So in a on_member_join - event this should work?
pfp = member.User.avatar
why the User
so just member_avatar?
discord.Member.avatar
.
where discord.Member is replaced with an instance of it
so just member.avatar
ok ty
Well uhh now I get this output: c931c5ef1b7a77fcb19138b84b81fd0d @slate swan
target=discord.utils.get(ctx.guild.roles, name="everyone")
How can i make this work based on names?
I get this error : raise InvalidArgument('target parameter must be either Member or Role')
avatar returned an Asset object
Can you somehow check if channel_id can be sent a message?
no slowmdoe or anything
don't use that method
told u it's not worth it
use ctx.guild.default_role
what about other roles?
wdym
other than default
don't you wanna get @everyone
Asking in general
So what do I do it doesn't? I can't resize a string xd
it's not a string
maybe save it
that's probably what save does
Well yes it is because when I try to resize it it gives me an error that a string cannot be resized
hmm?
did you try to resize an object, that was defined by the library, with a built-in function?
!d discord.Asset.save
await save(fp, *, seek_begin=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Saves this asset into a file-like object.
assign this to a variable
pfp = member.avatar.save()
with my logic, it should work and be resizeable
it could definitely be wrong :bruhkitty:
Let me try
Well now it says:
AttributeError: 'str' object has no attribute 'save'```
xdd
bro wat
it can't return a string
Bru I'm just trying to do a welcome message with image manipulation is it that complicated xddd
Could it be because of the wrong version?
that would be the only explanation
@slate swan To install the new version. Do I just have to do pip install discord.py -- upgrade
or smth like that
no
you need a github url
pip install -U github_url
which I currently can't find
i see
how to get id of the role with just it's name
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
why when i run
python --version```
It says
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
is it possible to get a bot's invite link
only from the dev portal
No?
Lol just get the bot ID and the permission integer and u can make the invite link yourself
what the
hello
https://discord.com/oauth2/authorize?client_id=<BOT-ID>&permissions=<PERM-INT>&scope=bot%20applications.commands
@slate swan
omg actually
Hahaha
That is how I am making the invite link
I ain't hardcoding it but getting the bot's ID
bot is private
@slate swan Okay Bro got it now. But I have to save it as a png file to send it. Is there a way it auto-deletes itself after 10 secs or so? Because if don't my whole server will be full of those welcome images xddd
you mean that the message deletes itself?
send has a delete_after kwarg

it accepts seconds as float
No not the message. The PNG file
In my folder
!d os.remove
os.remove(path, *, dir_fd=None)```
Remove (delete) the file *path*. If *path* is a directory, an [`IsADirectoryError`](https://docs.python.org/3/library/exceptions.html#IsADirectoryError "IsADirectoryError") is raised. Use [`rmdir()`](https://docs.python.org/3/library/os.html#os.rmdir "os.rmdir") to remove directories. If the file does not exist, a [`FileNotFoundError`](https://docs.python.org/3/library/exceptions.html#FileNotFoundError "FileNotFoundError") is raised.
This function can support [paths relative to directory descriptors](https://docs.python.org/3/library/os.html#dir-fd).
On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.
This function is semantically identical to [`unlink()`](https://docs.python.org/3/library/os.html#os.unlink "os.unlink").
Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.remove` with arguments `path`, `dir_fd`.
New in version 3.3: The *dir\_fd* argument...
the guy literally linked the docs above you
yep, it has many informations since it's really official lmao
Hey, is there a way to refresh a message in every x minutes/seconds using backgroundtask?
refresh a message?
Yep
I'll give you an example
In staff list channel, I want to refresh that list every day so when new staffs joins the staff team, there are being listed in the list
So it should be refreshed to give you the correct number of staffs
Like the stats bot he refresh the number of members
I want to do that in a channel with an embed for exemple that is being refreshed
!d discord.abc.Messageable.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
How?
I havent done it before so im not sure
however, i assume your bot will stay online most of the time,
you can simply store the message object as a variable and use it and if your bot goes offline, you may somehow indicate to fetch it again
My bot is hosted 24/7 so no worries
so you can just store it as a variable as pass it, and if your bot goes offline, fetch it once and store it again
otherwise I think you can use the pickle built-in module
to store it to a file and load the object
Use a task.loop
dpy asynchronous tasks
How to make a condition that if the author has no roles then
Why is my bot going offline a lot 
join = "".join(x)
await ctx.send(f"```odbanowano {join}```")``` how to send it as file??
!d Membe.roles
if len(message.author.roles) == 1
This is how I did it. I was told @.everyone was a role so thatโs why itโs 1
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [โ@everyone](mailto:'%40everyone)โ role.
These roles are sorted by their position in the role hierarchy.
I don't need documentation
Naturally this would make it be the message author roles, just thought Iโd clarify 
thanks you
then dont ask for help here please, thats the only source to learn to use
at least read the docs
Np 
How are you managing to blindly write code without consulting docs?
@sullen shoal It is someones pfp i'm using PIL
so their pfp is by default transparent or you rounded it
I rounded it by doing this:
def circle(pfp,size = (215,215)):
pfp = pfp.resize(size, Image.ANTIALIAS).convert("RGBA")
bigsize = (pfp.size[0] * 3, pfp.size[1] * 3)
mask = Image.new('L', bigsize, 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((0, 0) + bigsize, fill=255)
mask = mask.resize(pfp.size, Image.ANTIALIAS)
mask = ImageChops.darker(mask, pfp.split()[-1])
pfp.putalpha(mask)
return pfp
Idk if it's good or not, copied it from Github
you can also directly insert the alpha channel into the image using numpy
Hi, how can I call a bot command from inside another bot command
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function.
so I dont need get_command?
!d discord.ext.commands.Bot.get_command
get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
it would be something like,
await ctx.invoke(bot.get_command('queue')
yes
why is there no ctx in this one?
ctx stands for Context
when you use the decorator to add a command,
the lib will pass the Context as the the first argument.
You can call it whatever you want
async def my_command(context):
await context.send('hello world')
How to reply with out ping?
I am trying to find the source code for the help command for the python bot but because I am pretty new I could not find it .
Can someone help me find it please???
here is the repo:https://github.com/python-discord/bot
thnx
Hey, im working on a purge command and im having some trouble with it, i want it to work of roles and not permissions, ive got it work, but when someone uses the command we want the bot to send an error message, for so reason it doesn't want to work
@Bot.command()
@commands.has_any_role(*roles)
async def purge(ctx, limit = 10):
await ctx.channel.purge(limit=limit)
embed = discord.Embed(description= "Cleared channel!")
await ctx.send(embed=embed, delete_after=15)
@purge.error
async def purge_error(ctx, error):
if isinstance(error, commands.MissingRoles):
embed = discord.Embed(description= "You don't have the permissions to do that!")
await ctx.send(embed=embed, delete_after=15)
ctx.message.delete()```
check the type of error
Hey @safe depot!
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:
you have to catch discord.ext.commands.errors.MissingAnyRole
raise MissingAnyRole(items)
discord.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: 'Gold command'
also message.delete needs to awaited
Can someone help me with this? Iโve never used apscheduler before and whenever I press one of the reactions, it gives me this error https://mystb.in/FeaturingLouisianaAdrian.python
Which one should I use for Danbot? (https://discordpy.readthedocs.io/en/stable/intro.html)
x?
await community.send(embed=embedCommunity,delete_after=5)
await channelSuggest.send(embed=embedSuggest,delete_after=5)
time.sleep(10)```
How come the time.sleep messes with my delete_after?
I wanna send a message, then once that message is deleted resend it. Basically keeping a pinned embed at the bottom of the channel.
I've tried asyncio.sleep but that made it spam lol
this is an asynchronous library, you use asyncio.sleep to not block your script
Well you see..
If you do asyncio.sleep(10)..
It sort of spams
while True:
await community.send(embed=embedCommunity,delete_after=5)
await channelSuggest.send(embed=embedSuggest,delete_after=5)
time.sleep(10)```
So uh any other ways xd
send the entire code of the command
@client.event
async def on_ready():
client.ready = True
await syst.log(xxx)
community = client.get_channel(xxx)
channelSuggest = client.get_channel(xxx)
embedCommunity = discord.Embed(description="Community")
embedSuggest = discord.Embed(description="Suggest")
while True:
await community.send(embed=embedCommunity,delete_after=5)
await channelSuggest.send(embed=embedSuggest,delete_after=5)
time.sleep(10)```\
also please follow the PEP 8 style guide
youre not supposed to do anything on on_ready
danbot ๐
what youre looking for might be, https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
on_ready is called multiple times
its doing the command, but its doing the whole command and not stopping at if statements even when theyre false.
@sullen shoal
is danbot some github repo
show code
#!q command -> Puts players into queue
@bot.command(name="queue", aliases=["q"], description="Join the queue")
@commands.check(is_issuer_in_game)
async def queue(ctx):
if ctx.channel.id in allowed_channels:
ggid = settings.find_one({"guild_id": ctx.guild.id})
game_id = ggid["game_id"]
qsize = ggid["qsize"]
pid = ctx.author.id
pmention = ctx.author.mention
if pmention not in playerqueue and len(lobby) < qsize:
playerqueue.append(pmention)
lobby.append(pid)
info = pstats.find_one({"id": pid})
if info is None:
newuser = {"id": pid, "Wins": 0, "Losses": 0, "MMR": 1600, "Rank": "C"}
pstats.insert_one(newuser)
embed = discord.Embed(
title=f"**{len(playerqueue)} of {qsize} players are in the queue**",
description=str(ctx.author.mention) + " has joined!", color=0xE74C3C)
embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(embed=embed)
if len(lobby) == qsize:
games[game_id] = lobby.copy()
lobby.clear()
playerqueue.clear()
game_id += 1
settings.update_one({"guild_id": ctx.guild.id}, {"$set": {'game_id': game_id}})
embed = discord.Embed(
title=f"**The queue reached {qsize} players**",
description="Voting is now underway!",
color=0xE74C3C)
embed.add_field(name="Vote for random teams", value="!r", inline=True)
embed.add_field(name="Vote for balanced teams", value="!b", inline=True)
embed.set_footer(text="CBell 6 Mans | Created by Heptix", icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(
embed=embed,
components=[
Button(style=ButtonStyle.red, label="Captains"),
Button(style=ButtonStyle.blue, label="Balanced"),
Button(style=ButtonStyle.green, label="Random")])
res = await bot.wait_for("button_click")
if res.component.label == "Captains":
await ctx.invoke(bot.get_command('r'))
if res.component.label == "Balanced":
await ctx.invoke(bot.get_command('r'))
if res.component.label == "Random":
await ctx.invoke(bot.get_command('r'))
#!r command -> Randomly sorts players into teams
@bot.command()
@commands.check(is_issuer_in_dict)
async def r(ctx):
if ctx.channel.id in allowed_channels: #and ctx.author.id in games.values():
ggid = settings.find_one({"guild_id": ctx.guild.id})
qsize = ggid["qsize"]
game_id = ggid["game_id"]
set_aid.add(ctx.author.id)
if len(set_aid) == qsize/2:
embed = discord.Embed(description="Random teams have been chosen",
color=0xE74C3C)
embed.set_footer(text="CBell 6 Mans | Created by Heptix",
icon_url="https://i.imgur.com/1utxX7d.png")
await ctx.channel.send(embed=embed)
when I click on one of the buttons, that invokes it, it sends the r command embed
when it shouldnt
oh hold on
I may be stupid
i dont see anything that says danbot there
I googled it, it looks like it might be some kind of hosting site
i see
Still confused as to what you're asking @elfin pewter
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1```
seems like they want to know which one to install to get their bot working there
which should be asked in their support server
it is included in the link I sent
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self, bot):
self.index = 0
self.bot = bot
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1
@printer.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()
it will wait untill the bot is ready then execute the printer loop
self.printer.start() this starts it
Can I put it into any cogs are got to explicitly use this one?
you can put it in any cog
Thank you that helped alot ๐
dont know, never tried, you should try it yourself
trying it rn ๐
Which should I use installation for Danbot Hosting project?
^
I'm not sure, that would be something you need to ask them
Doesn't work.
import os
import discord
import time
import datetime
import asyncio
from discord.ext.commands import cooldown, BucketType
from discord.ext import tasks, commands
import syst
class EmbeddedCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@tasks.loop(seconds=10)
async def test(self):
channelSuggest = self.guild.get_channel(xxx)
channelHelp = self.guild.get_channel(xxx)
embedSuggest = discord.Embed(description="xxx")
embedHelp = discord.Embed(description="xxx")
await channelSuggest.send(embed=embedSuggest,delete_after=10)
await channelHelp.send(embed=embedHelp,delete_after=10)
asyncio.sleep(12)```
Doesn't make errors and doesn't execute on_ready.
where is self.guild
Okay fair point..
Since it isn't being executed via cmd..
I have to define guild?
I don't remember how, so like guild = self.get_guild(id) ?
Or way off xd
self is the instance of the class, the attribute bot is discord.ext.commands.Bot instance of your bot
Can someone help
Yeah I know.
But don't remember how to define guild
I figured you didn't need to define guild.
Since it gets the channel?
to get the guild object by ID, you can use Bot.get_guild
read it carefully.
When I use bot it doesn't work
says bot isn't defined everytime
okay i see, your problem is something else
You don't have to define it defining channels.
I know how to use classes why did you send that
it will help with it. learning it today will help you forever
well i wont waste more of my time. good luck
hi
so i am trying to make a bot
and one of the commands i have set up is basically uhh
i have a txt file with phrases on different lines
and i want to print out a specific phrase, but i also want to print/get the line it's on
does that make sense?
btw you may type two lines by the shortcut, shift+enter
i think str.find()
will work for you
thanks!
Actually I'm not sure if this is what I'm looking for
you may give me an example of your input and output
How can I do that?
maybe you want something like,
mytxt = '''hello
world
xxx
707'''
phrase = input("enter the phrase: ")
phrases = mytxt.splitlines()
for index, p in enumerate(phrases):
if phrase.lower() in p.lower():
print(f"found phrase: {p}\nline: {index+1}")
?
The string is in a separate text file
hello good friends
you may use the open builtin function to read it
can someone give me a link to the tutorial for discord. py
that is commonly linked
however its not async so it will block the code
well that's interesting https://discord.com/blog/discord-bots-and-app-discovery-announcement
there's no need for a tutorial if you know how python classes, OOP and decorators work then just the examples at https://github.com/Rapptz/discord.py and the docs, https://discordpy.readthedocs.io/en/master is enough
thanks
self.cogs = [
{'name': 'Minecraft', 'obj': minecraft.Minecraft, 'active': True},
]
self.init_cogs()
def init_cogs(self):
for cog in self.cogs:
self.bot.add_cog(cog['obj'](self.bot))
It doesnt upload the cog



