#discord-bots
1 messages · Page 652 of 1
what do you mean?
to get the guild that the member joins, just use member.guild no need to do client.get_guild to get the guild object
Depends on the context
Try using an if else statement to check in an underscore is there or not, then loop through the lost words and check if any of them contain an underscore and split them from the underscore and replace the underscore with empty strings
Change the variable names 'cause every time you define "role" variable it overwrites the previous role variable
.. Please anyone?
can someone help me ? there's error but i couldn't fix it
import discord
import asyncio
import time
import random
client = discord.Client()
TOKEN = ''
@client.event
async def on_ready():
print("Worked as {0.user}".format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('阿巴阿巴'):
await message.channel.send('阿巴')
if message.content.startswith('滚'):
await message.channel.send('蛋')
@client.command()
async def nick(ctx, m: discord.Member, *, newnick):
await m.edit(nick=newnick)
await ctx.send('done')
#(whateverprefix)nick @.useruwant newnickname
client.run(TOKEN)
you cannot use .command() with discord.Client
Facts
..
On god
and you need process_commands in your on_message event
process_commands is not a thing in discord.Client again
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
where's on message event?
use this instead of discord.Client
ok
If they to commands.Bot
how?
just use the Bot object?.....
commands.Bot is a subclassed version discord.Client with more features
what? i am dum
and it comes with a commands framework
import discord
bot = discord.ext.commands.Bot(command_prefix='a prefix here')```
don't really understand
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@bot.listen()
async def on_ready():
"""Called when the client is done preparing the data received from Discord."""
print("Bot is ready")
@bot.command()
async def test(ctx):
"""A test command"""
await ctx.send("test")
@bot.listen()
async def on_message(message):
"""Called when a Message is created and sent."""
if message.author.bot:
return
... # your code
bot.run(token)
Here is a simple example
oh thanks
yes it worked thanks
I mean I’m using the command to add myself to the list
And it’s reading my commands and adding
If the bot cannot DM, it is going to raise a Forbidden Exception
No module httpx but there is a module httpx. Any ideas?
You can use try except to catch it
how did you run the file? show the command
hi @sullen shoal
hello
can i ask a question ? im not sure whether its related to python or not
yea sure
Have you installed it?
like recently i just play a discord game called erpg,
pip install it
and i have a mind map right now , is it possible to use python to solve human verification ?
recaptcha?
can i put screenshots here ?
if that's the asqlite designed by danny , you'd be using git
show
one sec
Possible? Yes but sounds like what you're trying to do breaks rule 5
oh so its against the rules ?
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Read this
its kinda self botting
how can I use images I stored on my PC on somehost?
Istg I'mma KMS now
let me google it up what is a self bot
What happened?
Import Errors happened
They can
@slate swan
!pypi aiosqlite3
Rip. Are you using a venv?
Its a moderation bot
how is that related?
It's extremely simple code to do that
simple if statement on on_message is enough
Can you tell me how to install or time waste??
does anyone else use somehost here?
So i have something like, I have a folder named utils and inside of it, a file named constants.py. So, how can I import from that constant file? I tried from utils.constants import * but says no module named utils and when I add a period before utils, it raises an ImportError
use pip along with git?.
Github?
Hey @slate swan!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Seems like more of a question for general
no git is different
No one was able to help and i came here since it's a discord bot question :D
where you importing it tho
yea i used it for some time
.utils.constants
you'd be using from .utils.constants import *
Doesn't work
thats how every bot works tho
Hello. Wondering how to solve this. Brotli is installed. Any ideas?
try again
can you use locally stored images on it? Do you need to upload it to the file directory or is there a different method?
Yea lemme try again
you need to upload it ofcourse , its no ways connected to your own device
I meant is there a different, more secure method?
Anybody ever encountered this?
dont think so
Folder named Acc generator

ping?
?
other than making your own api with flask and getting those images with raw requests lol
oh ok
it would be .utils
What does this have to do with a discord bot?
from .utils import constant
It’s a discord bot
You are using discord.Client
O lemme try
That library is a selfbotting library
Shit
Ok?
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
How is it breaking law
so im using a sqlite db to store afk members' ids. Is there any way to check if the user mentioned in a message is the same as the afk person?
It's breaking tos
Never knew that but ok
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@bot.listen()
async def on_ready():
"""Called when the client is done preparing the data received from Discord."""
print("Bot is ready")
@bot.command()
async def test(ctx: commands.Context):
"""A test command"""
await ctx.send("test")
@bot.listen()
async def on_message(message: discord.Message):
"""Called when a Message is created and sent."""
if message.author.bot:
return
... # your code
bot.run(token)
A simple example of commands.Bot framework
if that doesn't work, try os.getcwd() see the path
Please help
instead of using on_message to make commands
use the commands framework
Easier and much better
if "CustomActivity" == str(member.ActivityType.type):``` any alternatives for this?
Mk
check if message.mentions[x].id is stored in the db
or use list comprehension to make a new list of people mentioned mm
Yes and use commands.Bot
could you provide a small example as i didnt understand what you siad?
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
and initiate the bot with bot = commands.Bot
Refer to this
@sullen shoal its quite rude to ask but can i dm u ? need to ask more regarding my question
its okay if u dont want hahaha
if "CustomActivity" == str(member.ActivityType.type):``` any alternatives for this?
Just send it hwre
Instead of dmin, send your problem here
More people can help
each message contains a list like payload called mentions
each element in this list is a member object
so you check if the member id is in the db or not
to optimize it, you could do ids = [i.id for i in message.mentions] i.e. list comprehension
and check if any of ids comes in any in db
isinstance is better
use isinstance
if discord.utils.find(lambda act: isinstance(act, discord.CustomActivity), member.activities):``` ?
my dms are closed, you will get your problem solved faster if you ask here
i have act defined btw
if isinstance(..., ...):
... # do something
Not sure if this is any helpful but even a print line isn’t working https://mystb.in/ModesProblemNudist.typescript
You want to activities of members?
mhm
im new in coding , what i wanna ask is why self botting is against the TOS? isnt the uses of bot is to make our life easier ?
please correct me
Don't make that many requests/ API calls in an on_ready event
you could use a task loop
if isinstance(user.activities(0), discord.CustomActivity)```
when this guy's file was called typescript by the webapp, i knew it was some spaghetti
or a startup function
dont do shit in on_ready
Huh
python main.py
WARNING:discord.client:PyNaCl is not installed, voice will NOT be supported
cogs.config can not be loaded:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 843, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/runner/Acrylic-Original/cogs/config.py", line 65, in <module>
class config_buttons(discord.ui.View):
AttributeError: module 'discord' has no attribute 'ui'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 149, in <module>
raise e
File "main.py", line 146, in <module>
bot.load_extension(cog)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.config' raised an error: AttributeError: module 'discord' has no attribute 'ui'
It’s very spaghetti yes
Functionality first
Also, when I remove literally everything except for print, that doesn’t work either
Do the other commands in your bot works?
It’s commands.Cog.listener(), right?
Yes
Okay well, I could be wrong, but I think your bot is getting disconnected from the Gateway
Yeah, it’s still connected
When you are making that much requests
It’s literally just print at this point
After sometime, does the bot not respond at all and still is online?
No no, it responds to ever single command
That I’m ready event does not work at all
Only thing
Bruh no
why do you have client and bot
just use a single bot constructor
commands.Bot
bot.listen() is better
when it comes to on_message events
It's an external asynchronous listener
bot.command is right
commands.Bot is your constructor
bot.command() is how create and register a command
Look here
I am using bot.listen() for on_message events
Use that
I can explain you why but its going to be very long
So I am gonna put this in short
Line 21 you can change that bot = part to whatever you want
And then just call commands like that
on_ready event is called multiple times when the bot gets disconnected. its not completely ready to be able to send messages and stuff when its called.
This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
use commands.tasks instead
Just make it consistent
listeners (.listen()) and commands.Cog.listener() are asynchronous and external event listeners
That means, a listener doesn't override the default event but actually listen to the event as an external source
When you create a listener, it adds the event listener to bot and when the bot receives an event, it passes the event data to all the listeners that you created
when I create an event in main like on_message I can't use other commands
I’m not sure how to use commands.task, never seen that before
Maybe I have idk, does anyone have a link
yes that's because your message event is override the default one
how do u fix that
@bot.listen("on_message")
async def message_listener(message: disnake.Message):
... # code here
You can listeners
Not an on message
oops
They are external and they do not block each other
And my commands work
wrong message
All good
Thank you
Yeah that is good enough
I could explain on detail the differences between listeners and events
But that's lengthy
Oh you want me to make a loop?
And I am lazy
Didn’t want to do that though hmm
you can cancel the loop when the work is done
@tasks.loop(count=1)
async def task(self):
await self.bot.wait_until_ready()
... # code here
This will execute the loop once
because of the count kwarg
good day to learn something new, never used tasks.loop
That won't work
replitdb only works inside replit
or a repl
You cannot use anywhere else
you want a database like that
MongoDB is your best bet
replit db isnt async afaik
Yeah that too
MongoDB is a simple and easy to use database. This tutorial will show you how to use MongoDB with python and the python module pymongo. Pymongo is the offical MongoDB API that allows for you to easily perfor mdatabse operations.
Please Note: This is simply the basics of MongoDB in python, it is meant to get you started and give you an introduct...
This explains how MongoDB works and how you can use it
It uses pymongo
but you need motor
Which is the asynchronous counterpart of pymongo
Now personally I don't like this
no errors on console
@tasks.loop(count=1)
async def task(self):
await self.client.wait_until_ready()
for i in queue:
print("just testing to see if this works")```
@commands.Cog.listener()
async def on_member_update(self,before, after):
guild = self.bot.get_guild(645753561329696785)
member = after
if after in guild.members:
if 'a1b2c3' in str(after.activity):
role = guild.get_role(916271809333166101)
await after.add_roles(role)
else:
role = guild.get_role(916271809333166101)
await after.remove_roles(role)
Hey why do I get the error
discord.errors.NotFound: 404 Not Found (error code: 10011): Unknown Role
The role ID is correct
im gonna do try: and print errors
i doubt it is
Do you have an error handler?
have you started the task
await task.start()
Did you start the task?
Either in on_ready or a command
and guild?
if guild.get_member(member.id) is not None:
rich_presence = ":rich_presence:"
acts = member.activities
if member.activity is None:
act = 'None'
else:
activity_name = member.activity.name
a = ActivityType
if member.activity != None:
act = f'{member.activity.type}'.replace("ActivityType.playing", f"Playing {activity_name} {rich_presence}").replace("ActivityType.listening", f"Listening to {activity_name} {rich_presence}").replace("ActivityType.watching", f"Watching {activity_name} {rich_presence}").replace("ActivityType.streaming", f"Streaming {activity_name} {rich_presence}").replace("ActivityType.competing", f"Competing in {activity_name} {rich_presence}").replace("ActivityType.custom", f"{activity_name}")
if isinstance(act, discord.CustomActivity):
act = f'{activity_name} {rich_presence}'```basically trying to make the bot get status, if status is custom but rich presence is detected (playing, watching, ect), than output is (custom status + rich presence emote). if status is not custom but rich presence is detected, output is (activity type + activity name + rich presence emote). if no status at all, output is 'None'
Thats correct too, I checked like 3 times haha
i still doubt
💀 there you can check the guild id in the bottom also
alr sent the role id proof above 
tbh if smth like happens to me, i just delete the code and code it again with few extra brain cells and it magically starts working
Maybe the role isn't in the cache
try using fetch
I tried rebooting the bot 
it's an API call and a coroutine
okay
So you need await it
anyone?
class bdsp(commands.Cog):
def __init__(self, client):
self.client = client
self.trader.start()
# Sysbot.py
@tasks.loop(count=1)
async def trader(self):
await self.client.wait_until_ready()
try:
for i in queue:
print("just testing to see if this works")
# other stuff im asking the bot to do```
still not printing
await ctx.guild.fetch_role()
whats queue
didnt print exception either
you must be passing them then
I dont have a global one
i dont see queue defined
geez idk what im doing anymore
if guild.get_member(member.id) is not None:
rich_presence = ":rich_presence:"
acts = member.activities
if member.activity is None:
act = 'None'
else:
activity_name = member.activity.name
a = ActivityType
if member.activity != None:
act = f'{member.activity.type}'.replace("ActivityType.playing", f"Playing {activity_name} {rich_presence}").replace("ActivityType.listening", f"Listening to {activity_name} {rich_presence}").replace("ActivityType.watching", f"Watching {activity_name} {rich_presence}").replace("ActivityType.streaming", f"Streaming {activity_name} {rich_presence}").replace("ActivityType.competing", f"Competing in {activity_name} {rich_presence}").replace("ActivityType.custom", f"{activity_name}")
if isinstance(act, discord.CustomActivity):
act = f'{activity_name} {rich_presence}'```basically trying to make the bot get status, if status is custom but rich presence is detected (playing, watching, ect), than output is (custom status + rich presence emote). if status is not custom but rich presence is detected, output is (activity type + activity name + rich presence emote). if no status at all, output is 'None'
on_command_error
https://mystb.in/CatchCoursesBased.typescript
Keeps saying typescript but its just poopy code
who's good at cogs
queue is defined on line 42
u need help?
YES
sure
line 441 is the command im using to add myself to the queue
and I know its adding me to it
What is it
gib a sec
python main.py
Traceback (most recent call last):
File "main.py", line 32, in <module>
from cogs.extra import extra
File "/home/runner/Tirex-Safety-1/cogs/extra.py", line 3, in <module>
from utils.Buttons import ButtonPlate
ModuleNotFoundError: No module named 'utils.Buttons'
exit status 1
Utils.buttons
k
What k??
nicer way to say whats the problem
it won't be utils
if guild.get_member(member.id) is not None:
rich_presence = ":rich_presence:"
acts = member.activities
if member.activity is None:
act = 'None'
else:
activity_name = member.activity.name
a = ActivityType
if member.activity != None:
act = f'{member.activity.type}'.replace("ActivityType.playing", f"Playing {activity_name} {rich_presence}").replace("ActivityType.listening", f"Listening to {activity_name} {rich_presence}").replace("ActivityType.watching", f"Watching {activity_name} {rich_presence}").replace("ActivityType.streaming", f"Streaming {activity_name} {rich_presence}").replace("ActivityType.competing", f"Competing in {activity_name} {rich_presence}").replace("ActivityType.custom", f"{activity_name}")
if isinstance(act, discord.CustomActivity):
act = f'{activity_name} {rich_presence}'```basically trying to make the bot get status, if status is custom but rich presence is detected (playing, watching, ect), than output is (custom status + rich presence emote). if status is not custom but rich presence is detected, output is (activity type + activity name + rich presence emote). if no status at all, output is 'None'
Not utils.buttons?
idk if im missing anything more, if I incorporate it into the other command it works
no, if you want to import buttons do it like that
But if you guys can tell its controlling other device
error:Traceback (most recent call last): File "main.py", line 30, in <module> bot.load_extension("cogs.music1") File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension self._load_from_module_spec(spec, name) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 623, in _load_from_module_spec raise errors.ExtensionFailed(key, e) from e discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.music1' raised an error: CommandRegistrationError: The alias current is already an existing command or alias. code:```
bot.load_extension("cogs.tictactoe")
bot.load_extension("cogs.economy")
bot.load_extension("cogs.music1")
or
@untold token still having the same error 
You have a same command twice
No module name cogs.utils
It's not a cog issue but a command issue
but there isnt any other command like that in main
current is already a comman/alias
that's how import stuff from utils directory
Yeah
whats the issue?
You have the command twice
Same issue?
Its giving error
You don't have module.exports in python
What is it
if you have rich presence, so streaming playing watching ect, but custom status at the same time, i want my bot to send their custom status followed with the rich presence emote
Yes, like cogs
you guys giving up? 😅
but whats the issue
You can multiple commands in a single cog
on what?
but if they have custom status with NO rich presence, than the output is just the status
BRO IT WORKS TYY
the emote doesnt show
Yeah
just add if statements?
Cool
ive done that
was trying to figure out an issue in my spagetti code
cant figure it out : /
any errors?
one sec lemme get a few screenshots to show what i mean
send it
Huh then role ID is wrong
and no, no errors
hm
Fetch doesn't fail
I tried another role ID too
Its saying typscript but it isnt...
https://mystb.in/CatchCoursesBased.typescript
thats how bad lmao
Do you have proper intents enabled?
@boreal ravine make sense?
yeah
just change it to python smh
oh... lmfao
Okay
Bot is online but no responses on buttons
hmmm so the emoji doesn't show?
Means help
Uh
ya, but the emoji is valid
Code?
sec, ill get another ss
Errors?
Well that's weird
Why is it giving an unknown role error
You are not passing the Role ID as a string right?
import discord
from discord.ext import commands
from .utils import stuff
from discord import ui
class HomeButton(ButtonPlate):
async def callback(self, interaction): # callback is basically the built in event handler for the button instantiated by the individual class
view = self.view
but anyways kayle, line 79 its not printing
@untold token
nope
so idk what I messed up
BRUH
hm
it was an example
@boreal ravine
from .utils import stuff
whoops i forgot to reply to the message, anyways https://oml.wtf/AcUjmPlf
stuff meant your modules and files to import
Well, are you sure you are using the correct guild
wait so im kinda confused, so it doesnt use the right emotes?
Why?
it does, one sec ill type out what its meant to do
yes
To fix this
Btw do you know basic python?
That's a basic python issue
and you seem to lack that
You should learn python before making bots
if you want to import something from buttons
The you need to import like this
from .utils.buttons import bla bla
Like that
@untold token This is also causing a memory leak 💀
Huh what
rich_presence = ":rich_presence:"
acts = member.activities
activity_name = member.activity.name```
if user has rich presence (streaming watching listening to, ect):
output is (activity name + type + rich_presence)
if user has custom status:
output is (activity.name)
if user has custom status but rich presence:
output is (custom status activity.name + rich_presence) @boreal ravine
does that make more sense of what my objective is or
hm
ic, but can you explain to me again the issue?
Dn
when I add the on_member_update listner and the code the number of tasks go from 5 to uh a lot..
hopefully that makes sense lol
yep
hm
do you need the src again or
but here you only 'send' the activity name and emoji
you dont send the activity name + custom status
so just isinstance(act)?
What do I need to make a bot like invitemanager?
isinstance takes 2 arguments lol, and you can check for a variable using isinstance. have you tried checking if the author has a rich presence and a custom status if so send it?
thats what the final statement is for
or at least what its meant to do
hm
show me it
if isinstance(act, discord.CustomActivity):
act = f'{activity_name} {rich_presence}'```
Hey kayle, did you ever get a chance to look at the code or nah
Attempted relative import with no known parent package
I did, but I didn't know what it does sorry lmao
haha, all good
Huh
Its cool because it controls my nintendo switch
Can you show your code?
o why not just check if theres 2 activities and if there are, send both of them (custom and rich presence)
Well I wanna import from utils.constants into main.py
- main.py
- utils
- constants.py
i totally forgot and was a thing LMAO
The import line is there
then
from .utils import constants
doesn't work?
lmao
Wait I can't import from utils.constants?
No you can't
I need an init file for that or something?
Try with in init file ye
It's an enum tho
!d discord.ActivityType.custom
how would i check for it then? using if {} and {} == True
A custom activity type.
is it
class enum.Enum```
Base class for creating enumerated constants. See section [Functional API](https://docs.python.org/3/library/enum.html#functional-api) for an alternate construction syntax.
if isinstance(activity, discord.CustomActivity):
I did tell em this
so py list_ = discord.ActivityType.playing, discord.ActivityType.streaming, discord.ActivityType.watching, discord.ActivityType.listening, discord.ActivityType.competing if discord.ActivityType.custom and x in list_:
It says unused but I clearly use it.
No......
How do I fix?
So if I also have a cogs folder in the same directory as the utils one, how do I import stuff from utils.constants into one of the cog file?
well you can create a utils file in the cogs directory
My discord died 😐
can you try this? member.activities returns a list, you can check if the list has more than 1 value (the custom activity is gonna be first) like```py
if member.activities[0] and member.activites[1]:
...
I don't want to. I wanna keep cogs and utils folder separate tbh
Then give it some other name ig
you used on_ready 2 times
Well I forgot the exact reason why you need to do .utils in order to import stuff
Istg I fucking hate import errors
Lol
Well create an init file then do
worked, i probably never would have thought of that lol
lmao
Ye?
Use a listener
I used it two times on an unused error?
If you want multiple on_ready events
Sorry for this, but fuck that.
@bot.listen()
async def on_ready():
... # code
It's supposed to be for reaction roles.
with this, it creates an external event listener that listen to an on_ready event
and you can use multiple of them
Okay.
Then do it for reaction roles
oops
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
There
That doesn't fix my problem.
package
!pypi <package>
Can also use: pack, package, pip
Provide information about a specific package from PyPI.
Si.
You gave a blurry picture 💀
@client.event async def on_member_join(member): role = discord.utils.get(member.server.roles, id="916758393132306463") await client.add_roles(member, role)
are my code right?
i want if a member join its gonna add role
ok im def messing this part up
for i in queue: this is where the command stops working
yah i code this for my server only 🙂
no this won't work
this is old
First of all its member.guild
not member.server
then its member.add_roles(role)
What about this?
Yeah it will work, and the IDs need to be an integer
Not a string
It's on the line with add reactions, stupido.
why doesnt this work?
@bot.listen()
async def on_member_join(member: discord.Member):
role = await member.guild.get_roles(ID of the role) # get the role object
await member.add_roles(role) # add the role to member
thx very much 🙂
Still there.
how can you call yourself a bot coder???
add_roles.
and its message.add_reaction
add_reaction is a method of the message object
ok 13 yro
^
You just mad.
Did you enable intents in discord developer portal?
yeah
No need to be toxic
Yes, but that still don't work.
if a members name is "Hello" and i use a command where an argument is a member, and i type the name "hello" instead of "Hello", how can i make it work for both cases? instead of raising the infamous "member not found" error
and it's not bot.send_message
Your code is entirely wrong
^^ !!
Well I don't add ctx, because my event don't need context.
channel = bot.get_channel(ID)
message = await channel.send("stuff")
await message.add_reactions("emoji here")
That's how you do it
Did you take this code from some youtube tutorials?
pass the arg. as string then search from the members list.
Because it uses, old methods and attributes
Which are deprecated
its member.guild
can somebody please help me with this
not member.server
Did you enable member intents in discord dev portal?
For your bot application
variable names should not start with an Uppercase letter
oh ok
Then the event isn't triggering?
what
Do you have any other on_member_join event?
oh can i only have one
You have an event that add roles when a member joins the server
oh
You should use .listen()
ok thx
to have multiple listeners
u can have multiple if you use listeners
@bot.listen()
async def on_member_join(member: discord.Member):
... # code here
This creates an external listener that listens to this event
and because they are external, you can have multiple listeners of the same event type
so this should work?
Yes
Wdym doesn't work
do i have to uncheck member intents?
Errors?
No
nope
yeah
this isnt required
Wdym
smh nothing
Did you change it from an event to a listener
So bot.event to bot.listen()?
Oh alright
yeah
Hmm
isnt it discord.ext.commands.Bot?
its commands.Bot
and its bot.event since you are not in a cog
No?
You can use bot.listen in non cogs too
if you really wanna use discord module use discord.Client
ah, didnt know that
commands.Cog.listener() is the sub classed version of Bot.listen()
@weary gale
and I encourage bot.listen() because it's an external asynchronous event listener, which doesn't overrides the default event
I see
so this is what i have and it doesnt work
see .event overrides the default event with your custom event
import commands first
from discord.ext import commands
,-,
but a listener is external
When you create a listener, it adds the listener into the Bot instance and when the bot receives an event, it passes the event and data to all the listeners you created
screenshot?
oooohhh
@bot.event
async def on_message(message):
... # code
await bot.process_commands(message)
The reason why you call process_commands in a event is because your event will override the default event that dpy uses
process_commands is the method that process the message that is recieved and the checks if the message content is a command with prefix that was set
If there is any, it will execute the function related to name of the command that you set
but that's not the case in a listener
@bot.listen()
async def on_message(message):
... # code here
In here, you don't need to call process_commands
Because this is an external listener which doesn't override the default message event
and if you call process_commands regardless
your commands will execute twice
that's because dpy is already processing your message and then executing the function related to it
and when you add process_commands method
you are doing it too
there's one in my main.py
Provide a commands_prefix
dont use replit unless your project is private
why
Hmm replit for bot hosting
people can see ur token
Not good
if people find your project
no they cant
Not, if you have stored it in a env variable
but if it is set directly in the code as a string
Then yes
They people can see it
so what
Bot = commands.Bot(commands_prefix=iforgotiforgotiforgot)
o
Yea it works
Oh pog
Haha yups
lowercase bot like bot = commands.Bot(command_prefix='blahblahblah')
^
Proper naming
so do i have to change every command in my main.py
to lowercase
wdym
Yes
f
^
crab you use replit i forgot
ctrl + f
^
or if your on mac, command+f
and you have the replace option too
to replace you have to do it manually??? 🤔
💀
this has to be capital right?
mhm.
im too smart
Lamo
No..
oh
display_name = "Test1"
user_name = "Test2"
user_id = "Test3"
connection_string = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=C:\Users\samjo\Documents\Database2.accdb;'
)
connection = pyodbc.connect(connection_string)
crsr = connection.cursor()
sql='''INSERT INTO accounts ([Display Name], [User Name], [User ID]) VALUES (?,?,?)'''
crsr.execute(sql, (f"{display_name}", f"{user_name}", f"{user_id}"))
connection.commit()
client.run(token_id)
This works, But I want to loop into everyone in the server and get there dispay_name, user_name, user_id and then put it into the database, Can anyone help please?
@untold token so do i have to move the autorole command to main.py?
or can i leave it
this is its current state, and it still doesnt work
what
what does I mean
so just that command_prefix
Like a prefix
i cant remember hwo
anyone?
what database are you using
Access
Access?
Microsoft Access
Never heard of that kind of database
how?
ok that doesn't matter
what matters, Is I want to get user_id, display_name, and user_name
-_-
Is it an SQL based database?
Well I can't help you with Microsoft access, I have never used that database
I mostly use postgres
urgh
and mongoDB
Can you tell me how to get user_id and user_name
at the same time
for the same user?
And then print it out as a string?
for example
You need to use the SELECT statement
If you want to get the data from the table
for user in guild.members:
print(user_id, member.username)
@slate swan you want to add everyone in the guild to a database?
No I want to insert
yes!!!
Ah I see
and you need the user id and name?
yes!
Then you need use the insert statement
yes I know but how?
do member.name / member.discriminator
we need a for loop
i nearly ruined my bot
what exactly do you need from the name
do you want tea#9576 or just tea
tea#1234 is a username
tea is display_name
@untold token still doesnt work
If you want the whole user name
Then
str(member) returns member name like this
name#1234
So
user_id = member.id
user_name = str(member)
member_name = str(member)
member_id = member.id
okay
doesnt work?
that's easy, you can do that yourself
and insert it
do I need another cog, Or just do it in bot.py /main.py
you have a fancy " https://i.imgur.com/VvXuISZ.png
You can do it in a cog, in the main file
Wherever you want
lol ik
how
i just dont understand why it doesnt work
guild = client.get_channel(756504534897000528)
for member in guild.members:
if you use synchronous libraries in asynchronous code, it will block the entire process
Will this work?
that's channel
I just want to print it
You need a guild
it works for the same i think
so it would be client.get_guild()
do you get any errors?
ok and
nope
guild = client.get_guild(756504534897000528)
for member in guild.members:
print(member)
will this work?
then, what exactly isnt working?
idk
this would print the member object
and yes it work
if you want the name
oh its supposed to be an autorole command
then
well event
File "d:\Desktop\MaxTheBot\bot.py", line 106, in <module>
for member in guild.members:
AttributeError: 'NoneType' object has no attribute 'members'
you need the members intent iirc
guild = client.get_guild(756504534897000528)
for member in guild.members:
print(str(member))
Is the ID correct?
this?
yes
yea
Channel ID is different and guild ID is different
its on
and also change the Intents in your code
yes I know
wdym
you currently use Intents.default
This
@quartz void he doesn't know what are intents
This
It's the guild id
Same ID
omg, It's the guild_id
That's not wrong
for member in guild.fetch_members():
AttributeError: 'NoneType' object has no attribute 'fetch_members'
Well its returning None
Intents.default()
intents.member = True
Would work
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents = intents, ...)
@weary gale
It's just enabling the members intents
so this?
i have
discord.Intents.all()
Yup
Is the name of role correct?
yep
ok
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
does it matter?
Yes it does
where i put it
in your event?
yeahj
for member in guild.members():
TypeError: 'list' object is not callable
new errorrrrr
where do i put it
it's an attribute not a method
what do I do?
bruh in your on_member_join event
remove the ()?
ayyyy it works
Cool
BRUH
i dont understoodenating
I'm done
no pls
Bye
understoodenating
dont giveup on us
send me your code, I gotta spoonfeed
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents = intents, command_prefix = ["$", "$"])
@bot.listen()
async def on_member_join(member):
autorole = discord.utils.get(member.guild.roles, name = 'thisissupposedtobetheroleid')
await member.add_roles(autorole)```
@weary gale copy your code and send it
Bruh like literally
@slate swan i sent it
why does he have a fucking listen?
autorole = member.guild.get_role(ID)
await member.add_roles(autorole)
Its better
i already have an event
wait yeah it's wrong
no?
It is?
how?
.event overrides your default event
it still just doesnt work
wtf am i doing wrong
that means you can only have one event type
i feel like monke
.listen() is an external event listener
no
that is asynchronous and it doesnt block/ override the default events
try printing something to see if the event's triggered
@slate swan read from here
and
want me to fix the code?
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
Don't spoonfeed
ur right
it didnt even trigger
Code?
@bot.listen()
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, name='thisissupposedtobetheroleid')
await member.add_roles(role)
Bruh why would put the ID on the name
I stole it from my own code, AND YES IT WORKS
That's wrong too
It works man
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents = intents, command_prefix = ["$", "$"])
@bot.listen()
async def on_member_join(member):
autorole = member.guild.get_role(ijustremovedtheidbecauseprivacy)
await member.add_roles(autorole)
print("AUTOROLE TEST")```
And ID is sometimes better
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents = intents, command_prefix = ["$", "$"])
@bot.listen()
async def on_member_join(member):
role = discord.utils.get(member.guild.roles, name='thisissupposedtobetheroleid')
await member.add_roles(role)
print("AUTOROLE TEST")
