#discord-bots
1 messages ยท Page 580 of 1
why is the : an error
what is the extra ( doing
ยฏ_(ใ)_/ยฏ
....message is undefined
do it like this?
WAIT
ok
let me send another example
imma just copy my whole code to here but its too long
oh btw this is wrong because discord.Client doesn't have commands
bot = discord.Client(#all your info)
@bot.event
async def on_message(message) # define this here
only events
i do this?
what info
I mean the settings for the bot like command prefix
no
=.=
Yeah, I just realized. The convo is getting a bit confusing..
so what should i do
Uh, let me post another code.
just discord.Client() with empty brackets
async def show_help():
await message.channel.send('-rpm hunt/mine\n-rpm craft\n-rpm boss/defraid\n-rpm cd\n-rpm p\n-rpm inv')
just help me do it im very confused right now
i need to import anything?
import discord
import discord.ext.commands
Whew! The convo is getting even more confusing!!
Sometimes even there is no error, it marks. That is what happens on my side.
But it still runs
@bot.command
@bot.command()
async def do(ctx): #defined here
where do i put it
put ctx in the parenthesis, show_help(ctx)
ok
in the function definition
ah, you can pass message into show_help and use message.channel.send
@bot.command()
async def hei(ctx):
ctx.send("HE")
yes
Yeah
that wont work-
what have i added actually
async def show_help(message):
await message.channel.send(...)
...
if message.content.startswith("rpm help"):
await show_help(message)
still not showing btw
lemme try this
this won't work because it's message and not ctx
oh true...
what is ctx
context
still not working bruhhh
use this
..... check my code again
ok
so await show_help(message.content)
no
Yes!!!
Victory. ๐ฅณ
@slate swan you don't seem to know his code
I saw the code image posted on Discord
async def show_help(message):
await message.channel.send('-rpm hunt/mine\n-rpm craft\n-rpm boss/defraid\n-rpm cd\n-rpm p\n-rpm inv')
if message.content.startswith('rpm help'):
await show_help(message)
this is working but idk how
why (message)
message = message
async def show_help's message is imported from the @quaint axle.event message
oo
@loud junco in your on_message event you are checking the content of the message. If it starts with rpm help, invokes show_help and puts the message object into the show help function.
show_help then takes the message object, uses the channel.send method and sends the message
@quaint axle So sorry for mentioning
u mentioned again ๐คฃ
oh no
lol
-.-
-.-
i dun und but i will just throw message into the () everytime it doesnt work
Pain.
I understand...
its all on you
what class?
i guess cog class
func sure on top of codes
The same thing he just said. On the on_message event, you just get the message content. You then import it into the new function which uses a new input with the same value, then uses it again to create a further function that prints the well, help list!
a cog isnt a class its a subclassed class
and a subclassed class is a class
so i can use it on different rpm command right?
Yes.
For my mind, yes. I think so 0_0
o_o
I am having trouble reverencing the client within a cog
how do I send in the fancy boxes?
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
ill get there lol
lol not apostrophes
backticks, not quotes
it's below the Esc key
Show me your code
what
ok
why is it inside a print
Well I didnt see anything wrong there
class local(commands.Cog):
def _init_(self,client):
self.client = client
its at the left of 1
ok sorry
`
pretend that didnt happen
What seems to be the error?
seems fine to me
its __init__ with TWO underscores on each side
oh wait yeah
anyways, I have a cog called local, this works fine
what open said
but I am trying to call the client command later within the cog to get user input, for example
...
msg = await self.client.wait_for("message", check= ctx.author, timeout = 30)
ah, you have to use commands.command() in classes
that too
but I am curious how this doesnt work
the check isn't supposed to be like that
@nimble thorn ....
it should be a def function
ok
!d asyncio.Event
class asyncio.Event```
An event object. Not thread-safe.
An asyncio event can be used to notify multiple asyncio tasks that some event has happened.
An Event object manages an internal flag that can be set to *true* with the [`set()`](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Event.set "asyncio.Event.set") method and reset to *false* with the [`clear()`](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Event.clear "asyncio.Event.clear") method. The [`wait()`](https://docs.python.org/3/library/asyncio-sync.html#asyncio.Event.wait "asyncio.Event.wait") method blocks until the flag is set to *true*. The flag is set to *false* initially.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This class has been implicitly getting the current running loop since 3.7. See [Whatโs New in 3.10โs Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example:
yeah
the check isnt like that I said
Yea, it uses asyncio.Event
use
check=lambda m: m.author == ctx.author
Yes
that's not relevant
The bot calls a trivia api, and then prints a question and 4 possible reponses, I want to wait for a reponse from the user and then use that tell them if they are right or not
@nimble thorn
!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**...
this?
Didn't he wanna know how wait_for works tho?
his check is wrong
what i said
pip install discord.py
im using replit
open the package manager and install discord.py
download the module
type this in the shell
replit should automatically do that tho
only if there is a requirements.txt right?
its ok rn
ya its weird
not really
nope, it uses poetry
I don't think thats how "IDEs" work
wtf
xd
how do i do this to class
for digit in number:
print(digit)
make a function and put that in there
a class?
wait do what to class?
print all of this
msg = await self.client.wait_for("message", check=lambda m: m.author == ctx.author, timeout = 30)
so then this should work?
isit even legal to put class in class ๐คฃ
yes
ok then its fine
yeah although you should be using a dict instead
replit is always diff from other ides
but i cant print dict attribute
ยฏ_(ใ)_/ยฏ
can some one help me how to create a bot
you can
why not
it will show the __dict__ thing
no
Huh
wtf
wtf you dont need that to print a dict??
you should know basic python and be aware about asyncio for that
You'll need to learn at least the basics first, and then come here if you have a problem
ok ty
who's "pepo"?
u will cry like how i do now
people
Awesome it does now, thanks gamers
when did people do that
i googled
thats for something else
dir()??
with the vars()
thats completely irrelevant-
!e
a = {"a": "b"}
print(dir(a))
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
ya
not related at all
it will show tons of these
why though
idk
why do you want to use dir
how dont you know
i googled how to print attribute in dict
yeah no please learn basic python
and it shows me that
which attribute do you want to print...
i know how to print one by one
but i wanna make it something like for loop
auto print
iterate through the dictionary
There is not a definitive way to embed two full sized images into an embed right, its one image, one thumbail and a footer right?
so person.age is for class and person['age'] is for dict?
yes
pretty sure
ok thats what I thought I just wanted to make sure, thank you!
You can also use person.get('age')
wtf no why
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
what is this
That's another way to get values from dictionary's
but its weird
means you need to learn more python before making a bot
yes
It's a link to resources that should help you understand what this code is doing a little better. It might be helpful for you to learn a few things like introductory OOP, data types, etc before jumping into discord.py
yes please learn the basics
At the end of the day it's up to you, but I would recommend learning a bit more as you will understand your code and your help a little better
oo okok
ye
Inv_total = {
mobdrop = {
cooked_pogchop = 0
}
misc = {
cobble = 0
}
illegal = {
bedrock = 0
}
}
do i did something wrong?
!e sorry I forgot to show you this example. ```py
data = {"key 1":"value 1", "key 2": "value 2"}
print(data.get("key 1"))
@undone wyvern :white_check_mark: Your eval job has completed with return code 0.
value 1
!e ```py
data = {"key 1":"value 1", "key 2": "value 2"}
print(data.get("key 1") == data["key 1"])
@undone wyvern :white_check_mark: Your eval job has completed with return code 0.
True
@boreal yarrow ^
but its weird
why dun u type less word
what about a dict in a dict
can u make an example?
Some people prefer using get. It doesn't actually matter as long as you are consistent with what you use
how to make a bot dm me when ever it come online??
like what to add in the on_ready event? using discord.py
Yeah but what's the point, what's wrong with doing it normally?
Some people prefer one way over the other
I know discord.py does, or at least used to use get.
but why dm
why dun u just make it show on console
its pretty obvious also
i am using console right now
my console is rigged just now
but when i am hosting it, i use replit so i dont check console
im using incognito's replit
oo
its just at the right of ur code?
ye thats y dm
ik
lol
but would prefer it to dm me
You should use a task, not on_ready because on ready doesn't always get called.
someone show me a syntax example?
i even tried it as a command, but did not work with id. need to ping
Let me try and find an example of a task for you.
ok
!e
a = {
"b": "c",
"d": {
"e": "f"
}
}
print(a)
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
{'b': 'c', 'd': {'e': 'f'}}
i used this (cogs)
async def dm(self, ctx, user:discord.User):
await user.send("I am online")
await ctx.message.add_reaction(":white_check_mark:")```
nope
this works^^. but using id wont
meaning?
i mean you can
It might be easier to write the dict on another line as a variable, and just put the variable in the dictionary
when i use ^dm @09๐ค๐ฅ๐ฌ๐ฐ๐ฑ๐ฏ๐ฆ๐ก๐ข๐ฏ#9678 it works. but ^dm 680014609226399878 does not
also i dont want the mention part
just using ^dm should dm
Are you using a discord.User/discord.Member typehint?
u cant have a dict in a dict in a dict?
well it should I dont know why it isnt working 
you can
what if i want 2 dict in a dict
discord.User
you can
You can also do that
how
it wont works if the user has its dms closed
This is a stretch, but try discord.Object
If that's even a thing anymore
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create โminiatureโ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the objectโs hash.
wait i got it now for id.
Inv_total = {
{
'pogchop' : 0,
'cooked_pogchop' : 0,
}
{
'cobble' : 0,
}
{
'bedrock' : 0,
}
}
but can u make it without id or mention just ^dm
that looks like JSON
Same way as you would pass multiple values. I think you should check out #โ๏ฝhow-to-get-help, and claim a help channel
LOL
Why not just using discord.User
the lib will fetch the discord user if it doesnt find him in the cache
It does make more sense, but since it doesn't appear to be working I'm just experimenting.
i want it to dm me when i use ^dm and not ^dm @09๐ค๐ฅ๐ฌ๐ฐ๐ฑ๐ฏ๐ฆ๐ก๐ข๐ฏ#9678 or ^dm 680014609226399878
Also as I said it wont work if the dms are closed. Did he mention the error?
nope
Nope
Dm yourself?
someone help
;-;
looks like python hate json
Once again, I think you should see #โ๏ฝhow-to-get-help and get a help channel, as this doesn't seem to be a discord.py question.
It's fine
If you would like, you can ping me in your help channel and I'll come over to help.
it works
something like this I guess?
Inv_total = {
"food": {
"pogchop" : 0,
"cooked_pogchop" : 0,
},
"blocks" : {
"cobble" : 0,
"bedrock" : 0,
}
}
now when i print ctx.author it shows 09๐ค๐ฅ๐ฌ๐ฐ๐ฑ๐ฏ๐ฆ๐ก๐ข๐ฏ#9678
and when i try
await user.send("Test")```
It returns a error
@thick sigil
u cant send something to a string
your supposed to get that user/member object first then use .send()
.get_user()??
get_user(id, /)```
Returns a user with the given ID.
ok
i dont get what u are trying to do, why just not using dm command with the user
Considering you previously got the author, you can simply use ctx.author.send
it has already been told
No it hasn't
@slate swan
Kayle talked about using get_user, which is not needed
i dont want to use the command. i want it to dm without it. like on ready or on user join
then use member parameter from the event
how?
get_user/fetch_user with the id
ok
TypeError: Client.get_user() missing 1 required positional argument: 'id'
You need to give the user id
Code:-
async def on_ready(self):
await self.bot.change_presence(status=discord.Status.idle, activity=discord.Game(f"{prefix}help"))
print(f"Logged in as {self.bot.user} ({self.bot.user.id})")
user = discord.ext.commands.Bot.get_user(680014609226399878)
await user.send("I am online")```
^^
nope
why are u using the whole class
!resources please learn more about classes and objects before starting with dpy to get a proper understanding of how the library works then
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Use this
there is one called aiosqlite as well
Yups haha
!pypi aiosqlite I think it ain't on pypi
Oh nvm there is
Thanks ill try later
!PyPi psycopg2
Ah yea that
Or mongo db , motor module in asynchronous code
hey guys, can someone help me out, wtv method I try to get the member's info, it always returns None, I've tried guild.get_member(id) as well
if ">vcpermit" in message.content and message.author.id in self.mv:
guild = message.guild
c = str(message.content)
d = c.replace(">vcpermit <@!", "")
g = d.replace(">", "")
h = int(g)
m = discord.utils.get(guild.members, id=h)
e = self.mv.index(message.author.id)
f = self.vi[e]
vn = discord.utils.get(guild.channels, id=f)
print(m)
await vn.set_permissions(m, connect=True)
s = "<@" + g + "> has been permitted to your VC!"
await message.channel.send(s)
do you have member intents on?
also , dont use on_message events for commands ,
use discord.ext.commands.Bot
god so many variables
I mean it depends since discord.py is async
how is that library and this error related?
the error is coming from the library
And the lib seems pretty dead
no commits for the last 15 months
mhm
Maybe use aiosqlite instead
well , Lost Programmer , if you were looking for good examples : https://github.com/try-fail1/asqlite3
the github page has better examples than that on pypi
did you use the exact same code
its used in sql to store data in the memory and not disk
yea
Ah okay
its suggested to use the aiosqlite wrapper
its much easier to use , and maintained
you cant , since its meant to use with asyncio
if you want to test your sql queries
just use sqlite3 ( its inbuilt in python)
hm
I turned it on in the dev portal
and I tried this -
m = discord.utils.get(bot.get_all_members(), id=h)
but still no luck
I tried various other methods as well
like -
m = bot.get_user(id=h)
m = message.guild.get_member(id)
await it
!d object.await
object.__await__(self)```
Must return an [iterator](https://docs.python.org/3/glossary.html#term-iterator). Should be used to implement [awaitable](https://docs.python.org/3/glossary.html#term-awaitable) objects. For instance, [`asyncio.Future`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future "asyncio.Future") implements this method to be compatible with the [`await`](https://docs.python.org/3/reference/expressions.html#await) expression.
Okay
hm
nvm, this worked for me-
m = await message.guild.query_members(user_ids=[h]) m = m[0]
tysm for your time @slate swan
just await it
Cool
!src
its not awaitable
aiosqlite
its not working
which part
You're missing a ,
async def apply(ctx):
a_list = []
submit_channel = client.get_channel(906141169271062578)
channel = await ctx.author.create_dm()
def check(m):
return m.content is not None and m.channel == channel
for question in q_list:
sleep(.5)
await channel.send(question)
msg = await client.wait_for('message', check=check)
a_list.append(msg.content)
submit_wait = True
while submit_wait:
await channel.send('End of questions - "submit" to finish')
msg = await client.wait_for('message', check=check)
if "submit" in msg.content.lower():
submit_wait = False
answers = "\n".join(f'{a}. {b}' for a, b in enumerate(a_list, 1))
submit_msg = f'Application from {msg.author} \nThe answers are:\n{answers}'
await submit_channel.send(submit_msg)
am not getting any error but when i do the command its sending me all 3 questions that i have all at once
How do i make it send one question at a time
?
nvm forget it i made it work
Hi anyone know how to make a submit button to make it submit an staff application for then review in a particular channel?
u can only close an occupied channel @slate swan
So it prints like this? :
item = {
'mobdrop': {
'pogchop' : 0,
'eye_of_ender' : 0
},
'misc':{
'cobble' : 0,
'bed' : 0
},
'illegal': {
'bedrock' : 0,
'bedrock_trophy' : 0
}
}
########################################3
async def show_inv(message):
await message.channel.send('items')
for items in item['mobdrop'].values():
await message.channel.send(items)
await message.channel.send('misc')
for items in item['misc'].values():
await message.channel.send(items)
await message.channel.send('illegal')
for items in item['illegal'].values():
await message.channel.send(items)
##################################################
if message.content.startswith('rpm i'):
await show_inv(message)
The answers are:
["Soemth", "D"]
You trying to make minecraft??
rpg
Ok
Hi anyone know how to make a submit button to make it submit an staff application for then review in a particular channel?
Okay, you need slash command modules.
^
TypeError: 'NoneType' object is not iterable
My Code Goes Like This
@bot.event
async def on_raw_reaction_add(payload):
guild = discord.utils.find(lambda g: g.id == payload.guild_id, bot.get_guild("829221271568908319"))
if payload.emoji.name == emoji_thing:
role = discord.utils.get(guild.roles, name="Communist")
if role is not None:
member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
(Idk python or discord.py much, just learning)
guild IDs are supposed to be integers not strings
@paper scroll code
@bot.event
async def on_raw_reaction_add(payload):
guild = discord.utils.find(lambda g: g.id == payload.guild_id, bot.get_guild(int(829221271568908319)))
if payload.emoji.name == emoji_thing:
role = discord.utils.get(guild.roles, name="Communist")
if role is not None:
member = discord.utils.find(lambda m: m.id == payload.user_id, guild.members)
if member is not None:
await member.add_roles(role)
error at 3rd line
Hi evereone how learn make a discord bot with python ???
!d discord docs have a good tutorial on getting started!
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
Boiler with Python?
i have a leveling system with Mongo Db and when iam running the project i got error:
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed, Timeout: 30s, Topology Description: <TopologyDescription id: 618523a20690f738c0ef2286, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('DATA BASE LINK,) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('mydiscorddb-shard-00-01.0ic0k.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>, <ServerDescription ('mydiscorddb-shard-00-02.0ic0k.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('connection closed')>]>
?
Your internet connection
you need to connect every ip (theres a button for it I forgot where)
im new with culsters and mongo db
so i dont know how is this work
theres a button
when iam setup my culster
i didnt add any ip i select
allow anyone join
There is no error, your code got executed perfectly fine
It did exactly what you wrote
- Send the avatar url
- Send that weird message
he sent the class
i want bot ping
avamember.mention
ok thx so much
!d discord.Member.mention
property mention: str```
Returns a string that allows you to mention the member.
how do you have a command cooldown for a user (for example, they use ping, and they have to wait, say, 30 seconds to use it again?)
ty
moblist = {
'mainmob' : {
'pig' : False,
'cow' : False,
'sheep' : False,
'villager' : False,
'witherskeleton' : False,
'blaze' : False,
'enderman' : False
},
'notmainmob' : {
'angrypig' : False,
'zombie' : False,
'angrycow' : False,
'spider' : False,
'angrysheep' : False,
'skeleton' : False,
'nitwit' : False,
'pillager' : False,
'magmacube' : False,
'zombiepiglin' : False,
'silverfish' : False
}
}
############################################################
async def area(message):
if area == 1:
moblist['mainmob'] = False
moblist['notmainmob'] = False
will all of them become False again?
if some of them is True
is there any good recommendation for a image processing library thats not PIL? I need something that can do text rendering reliably and PIL is just too clunky for that
no it would just set 'mainmob' to False
so in that case
oof
moblist = {
'mainmob' : False,
'notmainmob' : False,
}
then how do i make them all to false
for item in moblist['mainmob'].values():
item = False
for item in moblist['nomainmob'].values():
item = False
like this?
For the @commands.cooldown(1, 30, commands.BucketType.user), how would I access the retry_after argument in the raise CommandOnCooldown?
Yeah, but item will be 'mainmob' and 'notmainmob', so you need another loop
so i need to do moblist['mainmob'].values() ?
Since item will be 'mainmob' and 'notmainmob', you know what you can change in that code
help
Use an error handler
yes, but I want to access the retry_after
but can i do this? if i wanna do it this way
Use an error handler
raise CommandOnCooldown(bucket, retry_after)
discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 27.62s
ok then
lemme read this thanks for the resource >:)
That's not for you, but for @velvet tinsel
rip
will this do?
Try it and see 
who knows how to set up my welcome message
Nobody, since you did it
how to make greeting messages.
which can be customized
Sorry for English I'm Russian
Use a database to store the message per guild, then use the on_member_join even to know when a member joins the server
It's okay, you're trying your best 
and can you recommend some free database
anyone have tutorial for replit database?
SQLite I guess
!pypi asqlite3
ะพะบะต
!pypi replit database
#bot-commands and replit has a section for it's DB

i have a level system made with Mango db and i getting this error when i try it :
raise WriteError(error.get("errmsg"), error.get("code"), error)
pymongo.errors.WriteError: db already exists with different case already have: [Discord] trying to create [discord], full error: {'index': 0, 'code': 13297, 'errmsg': 'db already exists with different case already have: [Discord] trying to create [discord]'}
levelling = cluster["discord"]["leveling"] i added my mango db link
and add the name of my database
what you mean create
"db already exists with different case already have: [Discord] trying to create [discord]'}
oh
so i have to remove discord
no
Will it work if I do
random_channel = ["channel1", "channel2"]
await random.choice(random_channel).send?
will that send to different channels?
ok
sqlite3 or asqlite3
@spiral frigate
why thats bad

the prefixes are gonna reset everytime the bot restarts
That will be the cache.
hm
If you want to build a nice cache it's more than just a dict.
what is the difference between sqlite3 and asqlite3
!async
Concurrency in Python
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function
To run the top level async function from outside the event loop we need to use asyncio.run(), like this:
import asyncio
async def main():
await something_awaitable()
asyncio.run(main())
Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().
To learn more about asyncio and its use, see the asyncio documentation.
like it's synchronous, but in fact it's the same in terms of code
Well it is not made by the same person so some things are different.
I just can't find anything on it and the code in the documentation is not robitb
writes this
conn = asqlite3.connect(':memory:')
AttributeError: partially initialized module 'asqlite3' has no attribute 'connect' (most likely due to a circular import)
code
import asyncio
import asqlite3
conn = asqlite3.connect(':memory:')
async def connection():
async with conn:
await conn.execute("CREATE TABLE table (plate INT)")
await conn.execute("INSERT INTO table VALUES (5)")
# connection is automatically closed
loop = asyncio.get_event_loop()
loop.run_until_complete(connection())
@spiral frigate asqlite3 is your file name?
python file?
yes or not
Yups
Whats your python file name
sqlite3
?
Idrk tbh, sorry
I don't understand you if these are abbreviations I can't understand I'm Russian
Oh that's my bad. I meant, I don't really know then, since that error comes when the file name and module names are same...
I just rename the python file
And it works?
anyone know how to capture which user reacted to my bot's reaction?
hey, Im trying to make a command that creates channels if the channel name doesnt exist already but it doesnt work. Not really sure
this is what I got
# Bot joins server/auto msg
@bot.command()
async def setup(ctx):
guild = ctx.guild
for server in bot.guilds:
if "bot-chat" not in server.channels:
create_channel = await guild.create_text_channel('bot-chat')
print(create_channel.id)
else:
await ctx.send("there is already a channel in this server with the name 'bot-chat'")
if "quotes" not in server.channels:
q_channel = await guild.create_text_channel('quotes')
print(q_channel.id)
else:
await ctx.send("there is already a channel in this server with the name 'quotes'")
it creates the channel but if the channel names already exist and u use the command it will still create a new channel with the same name
for discord, you need to use asqlite3
I just can't find any normal info about asqlite3
await member.ban(delete_messages=False)```
is this how u ban members without deleting their messages?
!d discord.Member.ban
await ban(*, delete_message_days=1, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
nevermind i got it :D
Lol cool
??
i get error with this
how do i capture reaction ??
rather with on_raw_reaction_add
sorry what?
another event
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
This requires Intents.reactions to be enabled. so how do i enable this?
it's enabled by default
dw about it
what did i do wrong then?
you used on_reaction_add
not on_raw_reaction_add
ohhh
riight , sorry my bad, totally forgot about it
lmk if it works
Ah
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
which payload?
Just sent the docs
async def on_raw_reaction_add(payload):
. . . .
you have two arguments currently
you only need one
which one should i remove
naming don't matter
but i need both args?
no
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesnโt require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itโs required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
Use this then haha
u can use payload.member after
and payload.reaction
wow thats cooL!
lemme try
still error๐
u mean like this?
oh u meant .member not .user
still error
hm
any idea why?
thanks for helping tho
oh it's payload.emoji
i tried that too
same error
that should work
!d discord.RawReactionActionEvent.emoji
The custom or unicode emoji being used.
lemesee
!d discord.RawReactionActionEvent.message_id
The message ID that got or lost a reaction.
the argument that this event takes
ah yea
an instance of discord.RawReactionActionEvent
he's using the global event to edit any message with 3 reactions?
my original plan was to create a ticket
when someone reacts
but idk how to do that so
create an command to send the message in a channel, and store message id
use the global event to check if the id is the same of message
and if the reaction is the target reaction
then, make your code
store message id of my own message that i sent in that channel through the bot , right?
no
like
!createTicketMessage <channel>
output:
bot sends a message in <channel>, stores the bot message, adds the reaction
when someone reacts to a specific message?
global event:
if payload.message.id == <message id>:
if payload.emoji == " emoji ":
print("okay")
hi is there anyway where I can make it so that my discord bot can show whether a user is on desktop or mobile?
the client or specific user?
bd plugin
hm
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the memberโs hash.
str(x) Returns the memberโs name with the discriminator.
specific user
yea
!d discord.Member.is_on_mobile
is_on_mobile()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): A helper function that determines if a member is active on a mobile device.
i have a permanent embed on a channel and when someone adds a reaction to it it opens a ticket
returns a bool value <true or false>
thats the plan
and has a web property 1 sec
just check
if payload.message_id == id
oh fr?
easy as that
where do i do that?
inside of your event
on raw reaction add?
inside a func too?
yes
so would I just do if user.mention is_on_mobile:
why mention
so would I just do if user.mention is_on_mobile:
#do thing
else:
#do smthing else
if member.is_on_mobile:
this func?
oh alright
user should be a Member instance, it looks like
new to this lol
object oriented programming knowledge is kind of a requirement
||java||
exactly
i know some java but not much
I like C# better

i know some c too
nothing about c# tho
ofc
??
thanks
i cant use message.channel.send here
so how do i send messages?
id is undefined
you have to replace it with your message's id
oh so i have to get message id first from first func
it says this when im clearly not on mobile
don't you have a message that you will keep in a channel
you can just right click on it in discord
and copy the id
scoping in python
isnt it specific to !start message?
.
my code
user can be on web?
it enters the if statement somehow
yeah idk how since im not on mobile nor do i have the discord app open on mobile
you have to store the id somehow
in your whole code
what you made is called a local variable and it's only usable within one function
if msg.author == 668936262509527081:
if msg == "https://tenor.com/view/spit-it-out-spit-disgusting-gif-16413711":
await msg.delete()
dm = message.author.create_dm()
await dm.send("https://tenor.com/view/spit-it-out-spit-disgusting-gif-16413711")```
i am trying to delete the msg from the user but this didnt work, something wrong?
whenever i try to del a bot from the developer portal it says invalid factor code because i have 2fa even tho i put the right code
Is ctx.message.author not the command invoker?
^
Ah fair enough. I haven't done discordpy Dev in a long time so forgive me
5 months now actually :/
ctx.author -> take ctx then take the author
ctx.message.author -> take ctx, then take the message of it, then take the author
what is ctx?
discord.ext.commands.Context instance
meaning it's the whole context
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
umm
it has... many attributes
its a variable?
you can use every object as variables
true
well anyway how do get message id?
not locally
store the variable
like that?
no, globally
search in google
?
umm
i'll google
not sure about that way
yeah shows syntax error
How to use error handler
๐ฆ
in discord .py?
Indeed
Yo I wana fetch my own id and give my self a role with a bot can someone explain how the fetch method works
is it like bot.fetch(userid)?
is it fixed now?
!d user.id
No documentation found for the requested symbol.
Wait
Im using Discord.py and Im trying to get the Discord userid of a user when they type into a channel.
The userid can be found when you go into developer mode, and right click on a username, there ...
Here is your answer
Thanks
Does anyone know how to make an error handler
Simple Error Handling for ext.commands - discord.py - error_handler.py
Thatโs not jt I wana know how to fetch a member with their id
Using the member to fetch
TypeError: can't send non-None value to a just-started coroutine what is this error
!d discord.ext.commands.Bot.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.
Thanks
โ[TypeError]raised whenever an operation is performed on an incorrect/unsupported object typeโ
Thanks
await dm.send("https://tenor.com/view/spit-it-out-spit-disgusting-gif-16413711") trying to do this, is https not allowed?
Send the full error
File "D:\Discord Bot\GitHub\ecrpgbot1v2.0\main.py", line 96, in on_message await dm.send("https://tenor.com/view/spit-it-out-spit-disgusting-gif-16413711") TypeError: can't send non-None value to a just-started coroutine
There should be something like a line 42 or something
edited
Check if itโs on the line
Ok
it worked thank you so much!
Whats dm supposed to be
if message.author.id == 305573693134733313: if "https://tenor.com" in msg or "tenor" in msg: await message.delete() dm = message.author.create_dm() await dm.send("https://tenor.com/view/spit-it-out-spit-disgusting-gif-16413711")
in on_message event
why do you need to create a DM?
msg = message.content.lower()
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
message.author.send u mean?
Yeah, I canโt remember everything
yes, message.author is a discord.Member object
Sweet.
Whatโs a ticket
idrk this error maybe it's because the bot just started
a ticket?

u know , a new temporary channel
well done
just for mods to talk privately with user when they have a problem
all thank to you
A DM?
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a โsecretโ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
no
a temp channel
and the overwrites is the only complicated thing
Wait, a small question, how does stuff like #help-cake work?
maybe
Itโs just switching channeled around categories
And muting a dormant channel
And closes it when they use !solved
Well Channel Opens > Channel Becomes Closed > Moved to dormant > Moved to available again
And pinning messages
Yes, thanks for the logic
lmfao
any advice?
im trying to use the logging module to try and make my console look a little bit more clean, but if i reload a cog that uses logging, it will cause each info and warn etc to print multiple times, any help?
os.system('clear')?
or silence the print's
idk whats printing and why its printing, but if you want it to not print...don't print it
thats not the issue, it will print multiple times if i reload the cog. The more times i reload it, the more times it prints
@commands.command()
async def test2(self, ctx):
self.log.info('Test Message')
Output:
2021-11-05 16:48:59 | Idea | INFO | Test Message
2021-11-05 16:48:59 | Idea | INFO | Test Message
thats after i reloaded it once
i don't
ctx.guild
you aren't using commands
use commands instead of doing everything in on_message
thats a great idea
but i want to create channel when user adds reaction
so i dont think i have an option?
iirc you can get the reaction message, and then the guild from that
yeah, using payload.guild_id, you can get the guild id, and then find the guild using that
or, if you are not in a dm channel, payload.member.guild
what u mean?
inside dm channels, there is no such thing as a Member
so if it is a guild, you can get the guild using payload.member.guild
and for the discord, you need to use a mongodb asynchronous motor
so this responds to itself
when it starts, adds reaction, then reacts to those reactions
how do you setup a py await user.send('example') mine i made doesn't work