#discord-bots
1 messages ยท Page 734 of 1
then tell-
Dude, you cannot go around telling people to google things. There is a reason they come here for help
fr
first of all are your parameters wrong
when doing a simple 1v1 game, you can just have a command where you challenge another member, it wouldn't be a good ideae to challenge yourself (pass that as an argument ) and someone else in a command
can u just give the damn code
ill learn okay jesus christ
I'll give you directions
Sadly we don't code for you. We guide you and help you facing issues.
Well I don't think anyone will spoonfeed u here since u don't learn by that
there you have it
he's just stubborn
We just telling him that none will spoonfeed 
Anyone?
fair enough
no help with music bots, sorry
Oh.
do you know how to use mongodb?
sort of, I used it a long time ago
Tho the question will better be suited in #databases
i asked and got ghosted ๐
Ouch
Calm down
it'll save him time in the long run
Not much advantage by using motor since its just pymongo with asyncio
i will i just wanna know why
profile = {
"userId":ctx.message.author.id,
"userTag":ctx.message.author,
"balance":0
}
collection.insert(profile)
this wont insert
after adding balance it didn't insert anymore
yo btw use str(ctx.author) and ctx.author.id
Could be that's the problem? ctx.message.author is a discord.User/discord.Member object
only the id is enough
And yea, that too
userTags can change overtime
it isn't sadly it inserted just fine with them
then with balance it just stopped
u got an error handler?
nope the bot just doesn't output anything
can you show us the insert that DOES work?
sure
profile = {
"userId":ctx.message.author.id,
"userTag":ctx.message.author
}
collection.insert(profile)
its aight
where do you get your info from? which site?
he is making an economy bot
its my own code
no, I want to know where you learned to use mongodb
but documentation info i got it from the docs and this guy on youtube called techwithtim
i haven't really messed around with databases that much so its quite new to me
yep
hey i am using the bot.group to have sub help commands like this
!help sound
but i want to make an error handler if the user uses a argument which isnt a part of the help group example
!help dsds
even if !help dsds is used to responds with the og help command
!d discord.ext.commands.HelpCommand why not use this
class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.
Note
Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).
This means that relying on the state of this class to be the same between command invocations would not work as expected.
the docs I see, are only using insert_one or insert_many
idk where he gets the insert from
yea, that is what I was also seeing ngl
its worked with both
could be a shortcut method
@bot.event
async def on_message(message):
badword = ["fuck", "shit"]
for word in badword:
if word in message.content:
await message.delete()
await bot.process_commands(message)
the code isnt working
what's your message?
u do message.content.lower()
still does not work
awdsdfucksadaw
the if statement can also be shorted
if any(list comprehension here):
Yea that too
if any(badword) in message.content.lower():?
no
do slash commands consume more memory than normal commands?
also, censoring can be nice, but users will always be smarter
No, I don't think so
generator expression will also work :)
example? not relevant to this case ofc
Oh didn't know
i dont know why but nothing works.. i also enabled member intents
do u have messages intent?
(i for i in ...) <-- generator expression, this will return a generator
yes i do
I feel like your on_message event isn't even triggering, you probably have another event overwriting it, if I were to guess
i meant to say messages intents... im just sick af sorry
mind showing your intents?
yes, am i not able to do a few of them?
ah
boom
that's the issue
use @bot.listen("on_message") and then name your functions something else
@bot.listen()
async def badwords(message):
badword = ["fuck", "shit"]
if any(word for word in badword if word in message.content.lower()):
await message.delete()
await bot.process_commands(message)
ill guess ill make a listen event
also remove the await bot.process_commands after doing this
yes, this is what i wanted to do
you're a smart guy
Sure he is
Cool!
thank you all guys
Also @slate swan
yw
yes?
Prevent using @bot.event. Prefer using @bot.listen() since the bugs are lesser with it
ok, thanks!
only thing missing is the return in the if statement
you don't need to do anything else if there was a bad word in that text I guess
Also, since the event is that small, you'd be better of just adding it to the other on_command
@bot.event
async def on_member_join(member):
channel = bot.get_channel(928979145365549097)
await channel.send(f"Welcome, {member.mention} to CactusDM server!")
also i have no clue why this does not work
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.
i do have that on
you don't
in code also?
yes
intents=discord.Intents.all()
and now in the bot constructor too?
you mean in the developer portal?
It'll work, ofc
still nothing
from discord import Intents
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix = '!', help_command=None, case_insensitive=True, intents=intents)
cool, and now the discord portal
restart the bot and it'll work
nothing
you don't have 2 bot instances, do you?
that is all
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.
do that, don't leak token
I hope this is for the correct bot
You most probably have another function named on_member_join
yes it is xD
yes i do
my god
(: that is the issue
I thought he learned his lesson after the on_message lol
You are shadowing functions
i didnt know you were not able to do the same event twice, i just dont like messing my code up lol
just organize one function, you can put it all in one
having a lot of small functions can be quite useless too sometimes
That's why I introduced you to @bot.listen() (:
He is such a gentleman
Its fine haha
one last useful fact: you enabled presence intents in the dev portal, but never enabled them in your code
just toggle that off in the dev portal
Ive made my own function, is it possible to get the guild_id?
wot
async def update_global_variables(setting, guild_id):
global server_guild_id
global server_name
global server_location
server_guild_id = client.get_guild(guild_id)
print(server_guild_id)
server_guild_id just prints None
and you thing he understands that? xD
print(guild_id)
Prints None ๐
means u passed None***
you actually want to use botvars, you'll thank yourself for that later on
you most likely are making a bot for only one guild
but if u wanna make linters happy, then u will have to subclass the bot class haha
@potent spear Im hoping to get it into a couple of guilds. my first time trying it ๐
not anything = nothing = none
storing guild_ids etc for what purpose?
Im trying to get it to compare it to a database to retrieve all the server information ๐
alright, the only thing you can store there is maybe the ID
the rest, you can simply acquire by getting the guild via the ID
for example
the guild name etc can be edited, no need to store that
guild ID is all you need
in the GUILDS table
Any idea how i can get the guild id from what i have above? ๐
tell us what you're trying and we'll simplify it for you
@potent spearIts for a game. logs all the kills and stores all the data from the server.
Im trying to save all the data on a database like above (Very basic so far) but using the guild_id as the unique code for each server
you're a smart guy with some coding background, am I correct?
like a bit of SQL, not too much python
Little ๐คฃ my first time trying to make a bot which can hopefully go into a few guils
well, have you ever used commands before?
commands?
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.
see what the bot did? based on the command, it responded with a message
yeah ive made commands ๐
alright, is your db implemented in your bot already?
Yeah it is, but i can easily change it
what library are you using?
discord.py and aiomysql
alright, I'm starting to like this
does your bot have a botvar with a db?
like bot.db = await aiomysql.connect(...)
so you can access the db wherever the bot is?
Yes sir!
okay?
guilds has guildID
members has user ID
and userstats has guildID userID kills, etc etc
yo anyone got an idea how I can search through this message? its an embed ```py
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
if payload.member.bot:
return
channel = bot.get_channel(payload.channel_id) or await bot.fetch_channel(payload.channel_id)
if str(payload.emoji) == "โ
":
msg = await channel.fetch_message(payload.message_id)
```
userstats has a relation with the guilds table and the members table
so whenever a guild gets deleted, all the info gets deleted from the userstats table too
๐ gotcha
userstats table can have columns with the same memberID, but a different guildID, you see?
the same user has different stats on different guilds
message.embeds[0], first check if it contains embeds ofc
then you can access the shit from the embed via its attributes
๐ฎ ahh ofcourse
you just need a good DB structure and you're all set
Ill re srtucture my DB like how youve said
Yeah, see i had an idea of storing all the bot details in one table
version, color, tag lines .etc
then the server details in another
I didn't pass message
and I don't think I can
guild_id,admin_id, any server settings
msg...
then all the player info
you can put that in the GUILDS table, the specific guild settings
but storing shit that can change is a no-go, like the guild name etc
make sure the playerstats are in relation with the other 2 tables, so if anything gets removed from the guilds or users table, the stats get deleted too
Do you have any idea why it wasn't retrieving the guild id from the code i sent above? just for future reference
I haven't seen the implementation of that method, you probably used it wrong
Confusing tables. think i get what you mean
async def update_global_variables(setting, guild_id):
global server_guild_id
global server_name
global server_location
server_guild_id = client.get_guild(guild_id)
print(server_guild_id)
server_guild_id just prints None
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
mhm
alright, so you want to keep the db connection for as long as the bot is running, you don't want to connect to the db whenever you need it
Yeah i had that in mind, wasnt sure the exact way to do it. at the moment im connectnig to the DB everytime i need to do something
Also ignore the f-strings i just quickly typed it up to see if i could get it working. i need to convert all my f-string querys ๐
yeah
put this above it and give me the output
print(f"{guild_id}, {type(guild_id)}")
would this work? py @bot.command async def overwrite(ctx, member_id: int, to_dict: str) perms = ast.literal_eval(to_dict) if "dict" in type(perms): pass else: raise ValueError("Invalid dict for overwrite permissions") member = await ctx.guild.fetch_member(member_id) perms = {"send_messages":False, "read_messages": True} overwrite = discord.PermissionOverwrite() for i in perms.keys(): overwrite[i] = perms.get(i) await ctx.message.channel.set_permissions(member, overwrite=overwrite)
bc the user inputs a dict of perms and i need to push those perms onto a different user
well, obviously a guild with ID 0 doesn't exist...
try it ๐
i did
then what happened
it just kept saying that TypeError
post the error if there's any
post full error
that type object cannot be iterated over
@potent spearNo, exactly ๐
then problem solved
you're just passing a bad argument to that function ...
are we allowed to send links to our bots here?
here
i made a bot that gets reddit memes, weather, math from wolfram alpha, advice, jokes and stuff
Coool
I think so
Can someone help me?
wait
sup
oh
advertising your bot really?
no
oh ill delete it
show your code we can feedback on that
btw did u guys know nasa has a bunch of cool apis, i use one for my bot called apod, shows astronomy picture of the day, really cool
nah i didnt knew that seems cool
Damn

ot but I'm thinking of making a chair API
F
I don't like useless API's that much ๐
install it in the package manager/shell
error says it all
ya heres an example photo
pretty nice
I donโt think there is one
It doesnโt work
So what do I have to do
there is
@slate swan Here are all of their available api's https://api.nasa.gov/
Oh Iโll check then
any good free apis u guys know of?
thank you 
theres a button called shell and theres a button for the package manager
ya i use the one called apod, but there r some others too
give the bot permission?
Iโll look into it, thanks
Ye but this error because the bot has no permissions on the server?
jeyyapi (images), some-random-api, public apis github, waifu.im (sfw, nsfw, images)
oke thx
๐ณ
give the bot correct permissions
chances are, you're editing or kicking an owner / a user with more(higher) permissions than the bot
.bm
Yes, but once I gave a link with a bot invitation where they were marked so that 3 permissions I gave only now with just the administrator's injuries and some people have a bot from the administrator's prermison and some do not
Do ?tag apis in the dpy server for more apis lol
well, just know that the bot can't edit shit from a user with a higher role
See here some of the API's you can use in your discord bot or anything - API's.md
Crunchyroll api 
But because the bot does not have administrator rights on all servers, it freezes the bot
.bm
๐ณ
How do I get message creation date and how accurate it is(is it accurate down to the minute or down to a second or more)?
Guys, it's normal that I'm trying to make a bot through my phone, but when I completely prescribe a command without errors, I get an error.
(My PC just broke down)
so what should i do now because i'm desperate every 2 days i get kicked out of the bot because of this. That some have it added to the admin's stuff. Some don't. I have to kick the bot from all servers and tell them to add again?
!d discord.Message.created_at
property created_at: datetime.datetime```
The messageโs creation time in UTC.
await ctx.channel.set_permissions(ctx.author)``` hello how can i change permission that ctx author can read this and write
How does one get the message intents?
How to start coding with python ?
(yes new )
discord.dev
is there any package i can use for the discord.py buttons?
and this ```py
intents.members = True
bot = commands.Bot(command_prefix="!", help_command = None, intents=intents)```
only bots in 75+servers will need it to process messages right?
.
๐
check Pins for more information
most forks have buttons
can you name one?
!pypi disnake
yo
hi
for what exactly?
just to clear up confusion from the past
@bot.command()
async def button(ctx):
await ctx.send(
"Please Verify yourself",
components = [
Button(label='โ Verify')
]
)
interaction = await bot.wait_for("button_click", check=lambda i: i.component.label.startswith("Click"))
await interaction.respond(content="Button Clicked!")
reddit memes
did you use PRAW or did you send your own requests to the API?
because your component label doesn't start with what u specified.
Thanks that help me alot but still confus where to code on android ๐ถ
await ctx.channel.set_permissions(ctx.author)``` hello how can i change permission that ctx author can read this and write
do it in an actual console to get the full traceback lol
what should i change it to?
Buy a PC honestly. A semi-decent laptop goes for around $300. Coding on phone isn't worth it.
whatever your button lable is
๐ฅฒ
well, it is โ Verify
i just dont get it, where should i change something?
sorry if i sound stupid this is my first time with buttons
Start saving up. It can be as low as $150 depending on where you live.
True but I need bot rn ๐ฅฒ

in the check,
i.component.label.startswith("")
the thing about coding on phone is you can do it on the go. instead of dragging your laptop or desktop pc with you
Well can't you wait until you have enough money for a PC?
If not, try repl.it or Heroku to run your code. Honestly I would still say it's not worth it but if you wanna do it, that's up to you. Good luck
Oof 150 USD here is like 600 of my currency here
i still get the same error
Except you'll be missing out on hundreds of things. Coding on phone is just lame. There are hundreds of reasons why you shouldn't do such a thing.
mind sharing few reasons?
Invisible characters
Just let me try to code on android if that is possible ๐ถ
Oof
I've seen around 6 people that code on mobile and ask for help about invisible character errors here
@quick gust tried also this response = await bot.wait_for("button_click")
idk
sorry
Just use a fork
Reading code is impossible, people always have indentation errors, its annoying and auto correct
i am using discord-components
thanks anyways ๐
- difficulty in typing
- as a result, you'll be working slower
- phones generally have lower specs than even cheap PCs, as a result you'll have lots of difficulties in coding anything more than a medium-sized project
- You will never find an IDE on a phone. You'll have to get by using text editors.
- Compilers. You won't be able to find many compilers out there, and even if you do, you know how slow and power-consuming they can be when running on a phone
- Smaller screen
- as a result of the reason above, coding for hours on a phone will strain your eyes
- you won't be able to take advantage of features such as debugger, etc
- you also won't be able to see a lot of lines of code, hence it'll be harder to write and debug your code
etc.
That aint a fork, end of discussion
switch to a fork, it will be much more stable
There's no substitute for a cursor and a keyboard. Coding on a phone just feels uncomfortable.
good point
idk this shi buttons are very hard to make
hello
i learnt how to make some with that package
would anyone know how to use
https://opentdb.com/browse.php?query=general&type=Question#
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.
auto correct can be disabled but yeah good points
have you tried termux?
Auto correct is useful in day to day life so it would be annoying going back and forth enabling it then disabling it
So which app to use for coding (until buys laptop ๐ฅฒ )
@commands.command()
async def eee(ctx,user : discord.Member,*,role: discord.Role):
await user.add_roles(role)
I would ask in #editors-ides
they aren't, just learn how to use them like how you learned how to use python
why this not working
I did in like 2017. Pretty annoying I must say.
follow pep8 when?
Use QuickEdit, it has syntax highlighting.
discord.ext.commands.errors.CommandNotFound: Command "eee" is not found
it's discord.Client.command()
gotta agree with the annoying part.. but it can basically run almost everything like a Linux machine.
Why are you using commands.command? You should only use be using that inside cogs
waittt
Ooh okk
perm_list = member.permissions_in(channel)
raises
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'permissions_in'
!d disnake.TextChannel.permissions_for use this
Has it been removed or something? I know it was there before
permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") or [`Role`](https://docs.disnake.dev/en/latest/api.html#disnake.Role "disnake.Role").
This function takes into consideration the following cases...
what happened to permissions_in?
it returns the members permissions in the channel
raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: No overwrite provided. ```py
@bot.command()
async def v(ctx):
overwrite={
ctx.guild.default_role:discord.PermissionOverwrite(read_messages=False),
ctx.me:discord.PermissionOverwrite(read_messages=True),
ctx.author:discord.PermissionOverwrite(read_messages=True),
}
await ctx.channel.set_permissions(ctx.author)
await ctx.message.guild.create_text_channel(f"Verify {ctx.author}", overwrites=overwrite)```
uh not sure
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
Your bot needs permissions
@spring flax removed
Hierachy
he has admin
The bot role must be above the role you wanna give to the member
yes?
i think so
how do I get the permissions which are True?
go check lol
I currently did indiviudal_perm = [perm for perm in perm_list].
I'd expect indiviudal_perm = [perm for perm in perm_list if perm is True] to work but apparently not
check if using an if statement, ```py
x = True
if x: #will execute if x is truthy
...
just remove is True
It should work
didn't work, same outcome
[perm for perm in perm_list if perm[1]]
``` perm returns a list of tuples, first value is the perm name and the second value is a bool
is there any way to bypass that
nope
huh are you sure
yes..?
ah thanks
๐
Unless you are a Discord engineer and edit the code of their API you can't change it 
raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: No overwrite provided. ```py
@bot.command()
async def v(ctx):
overwrite={
ctx.guild.default_role:discord.PermissionOverwrite(read_messages=False),
ctx.me:discord.PermissionOverwrite(read_messages=True),
ctx.author:discord.PermissionOverwrite(read_messages=True),
}
await ctx.channel.set_permissions(ctx.author)
await ctx.message.guild.create_text_channel(f"Verify {ctx.author}", overwrites=overwrite)```
yo when I do this line of code ```py
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
if payload.member.bot:
return
channel = bot.get_channel(payload.channel_id) or await bot.fetch_channel(payload.channel_id)
if str(payload.emoji) == "โ
":
msg = await channel.fetch_message(payload.message_id)
print(msg.embeds[0])
```
<discord.embeds.Embed object at 0x000002D2A4008820> I get that, how do I get it as text
@client.event
async def on_member_join(member):
print("join")
welcome_channel = client.get_channel(907967823681323038)
await welcome_channel.send(f"Everyone say hi to <@{member}>")
member_role = discord.utils.get(message.guild.roles, name="Member")
await member.add_roles(member_role, reason="Member")``` can someone please tell me why this doesnโt work? literally nothin happens. it doesnโt even print to the console.
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.
i have them enabled in both the dev portal and the code
Can you show your client's constructor
wdym
Show the code where you construct the client
=yo when I do this line of code ```py
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
if payload.member.bot:
return
channel = bot.get_channel(payload.channel_id) or await bot.fetch_channel(payload.channel_id)
if str(payload.emoji) == "โ
":
msg = await channel.fetch_message(payload.message_id)
print(msg.embeds[0])
```
<discord.embeds.Embed object at 0x000002D2A4008820> I get that, how do I get it as text
intents.members = True``` this is what i have for the intents
Yea, but show the client's constructor.. The Client(...) or the commands.Bot(...)
this? client = discord.Client(activity=discord.Activity(type=discord.ActivityType.watching, name="for $help"))
class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
is there a certain spot it has to go
It's a kwarg
How can I make this into a command for my discord bot?
So essentially I want it to go: >id SERVER_ID CHANNEL_ID
It's the same name as what you called the variable
Refer here
me?
No
lol
And your code seems to suggest you are selfbotting ๐ค
This server doesn't help with selfbots
i mean im tryna put it into a bot
Then why are you using discum and not a regular wrapper?
idk its a code i got from github
๐ค
HUH
WHAT IS THAT NAME
ah ok thanks @pliant gulch
Just the name of the selfbot patched wrapper ยฏ_(ใ)_/ยฏ
whats a patched wrapper ๐
A wrapper specifically made to make selfbots work again
If your making a regular bot. Use a regular wrapper
E.g discord.py
yo when I do this line of code ```py
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
if payload.member.bot:
return
channel = bot.get_channel(payload.channel_id) or await bot.fetch_channel(payload.channel_id)
if str(payload.emoji) == "โ
":
msg = await channel.fetch_message(payload.message_id)
print(msg.embeds[0])
```
<discord.embeds.Embed object at 0x000002D2A4008820> I get that, how do I get it as text
oooh ok
thx
now time to learn to code in python ig... aka learn to do something else then print("hello")
!d discord.Embed.to_dict
to_dict()```
Converts this embed object into a dict.
AttributeError: 'Message' object has no attribute 'description'
Could anyone link me to some kinda tuto to code a bot similar to restorecord which would allow me to re-add users to my discord server if it get's raided? (using oauth2)
you did something really fricking wrong
how can i host my own discord bot? i bought vps but what next?
fixed ๐
I would recommend danbot hosting - its reliable
SSH into your VPS, transfer the source code of your bot over to the VPS, then run the bot
The VPS might not keep alive though, if you on linux you can just use screen
how can i transfer this code? [i'm beginner]
Host the source code somewhere you can access or do an FTP which might be more complicated
E.g if you have your bot's source code on a github repo, clone the repo from your VPS
thanks
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Anyone know what this means?
You forgot to await a coroutine
yo {'fields': [{'name': 'ID', 'value': '717836234335977564', 'inline': True}, {'name': 'IGN', 'value': 'mictony', 'inline': False}, {'name': 'P M', 'value': 'mictony', 'inline': False}, {'name': 'STATUS', 'value': 'Waiting', 'inline': True}], 'color': 10038562, 'type': 'rich', 'description': '@Cicton#4678', 'title': 'Verification'} How would I get the name value ID value from this?
[apt --fix-broken install] why its dosent work?
json["fields"][0]["name"] returns 'ID'
json is supposed to be your JSON object variable of course. And 0 is the index of which field you want to read data from.
Hey, how do I check last letter in a command?
Not sure what is the best way to explain this, but I have a remind command. I want the bot to be able check if I want minutes, hours or days. The way I would do that is by this command -r 2d
d = days
h = hours
m = minutes
So is it possible for the bot to check if gtime ends with D, H or M?
@Bot.command(aliases=["r"])
async def remind(ctx, gtime: int = None, ):
if gtime is None:
await ctx.send("GIVE A FFFFFFF TIME IN HOURS WHEN U WANT TO BE REMINDED")
else:
await ctx.send(f"I GONNA REMIND U AFTER {gtime} HOURS OR SOMETHING")
await asyncio.sleep(gtime)
await ctx.send(f"{ctx.message.author.mention}")
that is an embed
Then you can go for embed.fields[index].name
!e
x = "32d"
print(x[-1])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
d
thx!
AttributeError: 'dict' object has no attribute 'fields'
its a dictonary
@slate swan Please don't try to ping @everyone or @here. Your message has been removed. If you believe this was a mistake, please let staff know!
Then this @kindred drum
Replace json with your variable
!e
x = {
"fields": [
{
"name": "ID"
}
]
}
print(x["fields"][0]["name"])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
ID
SOO my bot's playing the mp3 file once, but this error comes up and it doesnt play again
even tho its in a while loop
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
audio_source = discord.FFmpegPCMAudio('file.mp3')
if not voice_client.is_playing():
while True:
voice_client.play(audio_source, after = None)
await asyncio.sleep(10)
Anyone know how to fix?
the bot plays it once i run the command, but then i get: Error while decoding stream #0:0: Invalid data found when processing input and doesn't play again.
and whenever i run the command manually again, i keep getting this: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: Already playing audio.
@pliant gulch
Which prolly means that the while loop is owkring, so is the mp3 the problem?
You can shorten the first 3 lines to CTX.voice_client
As for your issue, its likely because voiceclient.play spawns a thread, it won't block till the audio is finished playing
That's what the after callable is for
oo, the mp3 file itself is 25 seconds, should i timeout for 30 seconds and see what happens?
bc its prolly overlapping audio i think?
That should work. Although I would recommend creating a system based on the after callable instead
wdym a system?
Some logic to play audio after the current audio is done playing
Which utilizes the after callable
def play_next(*args):
voiceclient.play(..., after=play_next)
``` this should loop the audio
perfect, let me try
so put everything in a function, put the. timeout outside the function and make it repeat?
You won't need a timeout
Well i want 10 seconds before the audio. repeats lol
Oh
yea
What im looking at is:
def play_next(*args):
...
while True:
play_next()
ayncio.sleep(10)
nvm okay
You shouldn't need a while loop at all
def play_next(*args):
voiceclient.play(..., after=play_next)โ
voiceclient.play(..., after=play_next)
After the audio finishes playing the first time, it will call play_next() which will play audio again, and it will loop
You can add time.sleep(10) before .play in the function to add a delay
a little lost here, how would the function be called again if you're not manually calling it?
oo
That's a terrible explanation
def recursive(a):
print(a+1)
recursive(a+1)
``` take this for example
If you call recursive (1) then it will print 2, then call itself and print 3 and so on
Yep
Yep
once the bot finishes playing the file, it leaves, rejoins the voicechat. You can hear the 'diding' thing on discord
its like for a split second
Make sure you enable intents though.
Could you send the code
its client.event() right @slate swan
No (), other than that it's correct.
@slate swan sorry a second
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
audio_source = discord.FFmpegPCMAudio('file.mp3')
def play_next(*args):
voice_client.play(audio_source, after = play_next)
await asyncio.sleep(30)
voice_client.play(audio_source, after = play_next)
the bot just leaves, rejoins, leaves, rejoins, leaves, rejoins, and then finally leaves
That's weird
@slate swan what do i do next
Print the member argument, that's will be the member who joined the guild.
Can i add the function with a timeout in after?
would that work?
Happy birthday, @slate swan!

def play_next(error):
print(error)
voiceclient.play(..., after=play_next)โ
``` set the function to this, see if it prints anything
No, I got work to do. 

the bot stopped joining the channel lol
it doesnt even join the channel anymore]=
lemme reset it
AttributeError: 'NoneType' object has no attribute 'poll_event'
it is, but it claims its not
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/lol/miniconda3/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: ClientException: Already connected to a voice channel.
^CTask exception was never retrieved
future: <Task finished name='Task-99' coro=<VoiceClient.poll_voice_ws() done, defined at /home/lol/miniconda3/lib/python3.9/site-packages/discord/voice_client.py:410> exception=AttributeError("'NoneType' object has no attribute 'poll_event'")>
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/voice_client.py", line 414, in poll_voice_ws
await self.ws.poll_event()
AttributeError: 'NoneType' object has no attribute 'poll_event'
@slate swan sorry can u explain it further
What's your code for connecting to a vc?
client.event
Is there a way to get a list of aliases bound to the commands on a serveR?
async def on_member_join?
@client.command()
async def join(ctx):
if not ctx.message.author.voice:
await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
return
else:
channel = ctx.message.author.voice.channel
voice = channel.connect()
await voice
Ok I can't figure this one out... my bot has all perms, admin + all the others checked individually. Can someone help me understand why I'm getting this error?
Yes, and add (member)
yup then
What are you trying to do with the bot?
For that you'd need to use get_channel
It restores members in the server in case of a raid
!d discord.Guild.get_channel
yes i did
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Then you can send, yep
Yeah but what are you trying? Banning, nicknaming, etc.
How do I make a string a id I can use to do x y z in discord py, like if I have a read a id and its now a string in a variable, how do I reassign it into a usable way
re-adding the user to the serv
I guess you'll have to add a check that makes sure you arent trying to connect to a channel which you're already connected to
You can't make users join servers with your bot.
pylance cant access
i mean it uses oauth2 and it got the perms on my account to do it
member @slate swan
Is there a way to get a list of aliases bound to the commands on a server? I am using self.client.commands currently, but I was hoping to access the aliases as well so I can list those as well
It's right though
proabbly cause i have to use member
Now you can continue by enabling intents and then you're done.
And its only 1 specific channel its bugging
yo whats the statement to get an user from an id? bot.fetch_user_id?
Haven't used that, but I think the python library has nothing to do with oauth
You'd need an oauth connection to be able to join a server, so via a website for example.
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.
Wanna have a look at the code of the bot?
@slate swan would this work
await when sending, then yes.
Yep - now you'll need to enable intents
intents?
Go to your developer dashboard, click on your application and to the left click on "Bot"
its undefined ๐ญ
Then enable the "Server Members Privileged Intent"
i mean oauth2 and requests
Then use fetch_user instead
I need help saving discord request.get and printing it in a payload to send text to discord. Can anyone help?
Don't use the requests library in an async library like discord.py
where
is there a limit on how old a message can be to edit it
done
now will it work
!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.
See the code part, you also need that.
97 days
weird cause i tried editing a msg and it said message not found
but when i try with a different one it works
Python Discord Switch Text from "A" to "B"
import requests
import json
def retrieve_messages(channelid):
headers = {
'authorization': ''
}
# need to make a request to the url
r = requests.get(
f'https://discord.com/api/v9/channels/{channelid}/messages', headers=headers)
# create JSON object
jsonn = json.loads(r.text)
# we can now use a for loop on this JSON object
for value in jsonn:
print(value, '\n') # new line as well to separate each message
retrieve_messages('883204140279414794')
payload = {
'content': ''
}
header = {
'authorization': ''
}
r = requests.post("https://discord.com/api/v9/channels/883204140279414794/messages",
data=payload, headers=header)
@slate swan
!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.
# Python Discord Switch Text from "A" to "B"
import requests
import json
def retrieve_messages(channelid):
headers = {
'authorization': ''
}
# need to make a request to the url
r = requests.get(
f'https://discord.com/api/v9/channels/{channelid}/messages', headers=headers)
# create JSON object
jsonn = json.loads(r.text)
# we can now use a for loop on this JSON object
for value in jsonn:
print(value, '\n') # new line as well to separate each message
retrieve_messages('883204140279414794')
payload = {
'content': ''
}
header = {
'authorization': ''
}
r = requests.post("https://discord.com/api/v9/channels/883204140279414794/messages",
data=payload, headers=header)
Why don't you use discord.py for this? Would make things much easier
Well, you're just sending messages right here.
So the bot apparently doesn't have permissions to send in these channels?
I want to link the two
the Retrieve messages and the send messages
to send a message when it receives one
Then you need a websocket connection to listen to messages sent.
Code?
!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.
Especially when you define client
the bot is only bugging in 1 specific voice channel, could it be permissions??
You're missing the intents part
Not sure, I've never experienced this
import discord
import random
import os
import math
import re
from discord.ext import commands
from discord.ext import tasks
from itertools import cycle
from discord import Intents
intents = Intents.default()
intents.members = True
#Desc loop
client = commands.Bot(command_prefix='!')
status = cycle([
'Ace Scrims discord moderation bot, made by Adrian and 0_0',
'Version 1.0'
])
Rule command
@client.command()
@commands.has_permissions(manage_messages=True)
async def rule(ctx):
embed = discord.Embed(title="Rules",description="Please read all the rules carefully.. \n 1: Do not spawnblock, Spawnblocking is very annoying and can be very unfair in matches for tiers. \n 2: No NSFW content. \n 3: Refusal to SS may result in a ban \n 4: Do not DM @Owners or @Staff \n 5: Read tier rules. \n 6: Do not advertise in this server. \n 7: Do not post malicious links or files. \n 8: Do not cheat in any server (Autoclicking counts), if you see someone cheating please report them to staff. \n 9: No innapropriate nicknames. \n 10: STRICTLY No racism or discrimination of any kind.",colour=0xFF0000)
await ctx.channel.purge(limit=1)
await ctx.send(embed=embed, delete_after=10)
#join message
@client.event
async def on_member_join(member):
channel = client.get_channel(914825862573064222)
await channel.send(f'{member} has joined the server.')
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
See the intents=intents part.
Hey @green bluff! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
oops
10/python.exe c:/Users/notvi/Downloads/Ace-Utilities/main.py
Traceback (most recent call last):
File "C:\Users\notvi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\notvi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\notvi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 666, in start
await self.connect(reconnect=reconnect)
File "C:\Users\notvi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 601, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000002106AF16290>
Traceback (most recent call last):
File "C:\Users\notvi\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\notvi\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\notvi\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Users\notvi\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
welp
time to regenerate my token
You haven't enabled in the developer portal.
Enable the one at the bottom
oops enabled presence intent
thanks it worked
same thing for leave except on_member_leave right
@slate swan
That one is different, it's on_member_remove
Since the event also gets fired when a user gets kicked or banned from the server, not only when a user leaves the server by themselves.
If you want to check if they only left and wasn't kicked, etc. You could check the audit logs for the user being kicked or banned
Andy would you be able to help?
Help with what
So the bot is wokring in every other channel except 1
It joins, rejoins, joins, rejoins, keeps doing that over and over again:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: Already connected to a voice channel.
if str(payload.emoji) == "โ
":
msg = await channel.fetch_message(payload.message_id)
msg_user = discord.Embed.to_dict(msg.embeds[0])
pre_user_id = msg_user["fields"][0]["value"]
user = await bot.fetch_user(pre_user_id)
role_id = 915553473653801031
roleobj = payload.channel.guild(role_id)
await user.add_roles(roleobj)
```
yo anyone know how to make this get the role? I just can't figure out the correct syntax for it
Can you show your code again rq
Yep
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/lol/miniconda3/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: ClientException: Already connected to a voice channel.
^CTask exception was never retrieved
future: <Task finished name='Task-99' coro=<VoiceClient.poll_voice_ws() done, defined at /home/lol/miniconda3/lib/python3.9/site-packages/discord/voice_client.py:410> exception=AttributeError("'NoneType' object has no attribute 'poll_event'")>
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/voice_client.py", line 414, in poll_voice_ws
await self.ws.poll_event()
AttributeError: 'NoneType' object has no attribute 'poll_event'
and also this when i shut the bot down
@client.command()
async def join(ctx):
if not ctx.message.author.voice:
await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
return
else:
channel = ctx.message.author.voice.channel
await channel.connect()
Probably because this maybe doesn't gracefully close the websocket which is keeping VoiceClient alive
@client.command()
async def leave(ctx):
voice_client = ctx.message.guild.voice_client
if voice_client.is_connected():
await voice_client.disconnect()
else:
await ctx.send('I am not connected to a voice channel')
How would i fix this?
Well can I see the part where it is playing the audio?
I havent even played the audio yet
?
So your bot for some reason thinks it isn't connected to a voice channel, but once it connects it is actually connected already?
it like joins, leaves, joins, leaves, joins, leaves, then just sits in the vc but it claims that its not in a voicechat
only in 1 specific voice channel
every other voice channel is working fine
For every voice channel other than the buggy one also joining and leaving?
Ok but a weird thing is that voice_client isn't actually a voice client
It's a VoiceProtocol
which doesn't even have a is_connected method
oo
if str(payload.emoji) == "โ
":
msg = await channel.fetch_message(payload.message_id)
msg_user = discord.Embed.to_dict(msg.embeds[0])
pre_user_id = msg_user["fields"][0]["value"]
user = await bot.fetch_user(pre_user_id)
role_id = 915553473653801031
roleobj = payload.channel.guild(role_id)
await user.add_roles(roleobj)
```
yo anyone know how to make this get the role? I just can't figure out the correct syntax for it
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
audio_source = discord.FFmpegPCMAudio('file.mp3')
if not voice_client.is_playing():
while True:
voice_client.play(audio_source, after = None)
Let me just check again to make sure although
This is my code where the bot plays audio
I hoped it'll play the audio over and over but it doesnt
so here's the updated:
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
audio_source = discord.FFmpegPCMAudio('file.mp3')
def play_next(*args):
voice_client.play(audio_source, after = play_next)
await asyncio.sleep(30)
voice_client.play(audio_source, after = play_next)
but even here it doesn't play the audio over and over
Can you print the voice_client var?
Lemme try
how to I find more information on discord.py and how to use it
The docs
is that a website
Thank you
Also, I would suggest you get started with a fork instead of dpy because development and maintenance on it has stopped
^
I would personally recommend disnake but peoples opinions differ
i use disnake
!pypi disnake
!pypi pycord
this one
<discord.voice_client.VoiceClient object at 0x7f575891d430>
Ignoring exception in command join:
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/lol/dsrp.py", line 44, in join
await channel.connect()
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/abc.py", line 1274, in connect
raise ClientException('Already connected to a voice channel.')
discord.errors.ClientException: Already connected to a voice channel.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/lol/miniconda3/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: ClientException: Already connected to a voice channel.
Even though its not in the voicechat
When i do -join, i get that in terminal^
But when i say -leave, it claims its not in a voice channel
And are you using this command to connect the bot
yes
The bot like joins, leaves, joins, leaves so fast =. its for like a split second, do you think its glitching itself out?
Well the issue in logic here would be, VoiceState (author.voice) isn't None meaning they are connected. But you never check if the client is already connected to the voice channel
ummm
What steps will fix this ?
Should i add another check that makes sure its in the voicechat?
Hmmm, you can try checking if Guild.me which is a Member instance representing the bot and check if it is inside of voice.channel.members
property me: discord.member.Member```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
Does someone want to hop on a voice call and help a buddy and I with a discord scrapper?
Just found something out
So
@client.command()
async def join(ctx):
if not ctx.message.author.voice:
await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
return
else:
channel = ctx.message.author.voice.channel
await channel.connect()
print('Im here')
added a simple print statement to see if its even joining once
Every other voicechat, the bot joins and i get the "im here"
but this bugged voicechat, i dont get the "im here"
which means its not joining at all
The thing is, the bot was joining and working just fine in this vc a couple hours ago, it just started bugging out a few minutes back
Can you set a var to channel.connect() and print that as well?
Since that will return the VoiceClient
yep
Also maybe the channel has permissions that stop your bot from joining?
<coroutine object Connectable.connect at 0x7f85be08b340>
Im here
/home/lol/miniconda3/lib/python3.9/site-packages/discord/ext/commands/core.py:85: RuntimeWarning: coroutine 'Connectable.connect' was never awaited
ret = await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
stoppd joining every other vc now
You didn't await the connect from what the error is saying
oop 1 sec
@client.command()
async def join(ctx):
if not ctx.message.author.voice:
await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
return
else:
channel = ctx.message.author.voice.channel
test = channel.connect()
await test
print(test)
print('Im here')
<coroutine object Connectable.connect at 0x7f181d7a1340>
Im here
<discord.voice_client.VoiceClient object at 0x7f181e8e3f10>
disconnected
lets try the buggy vc now
doesnt print anything in terminal
The bot just joins, leaves, joins, leaves
no wait
And if you remove the connect call when in the buggy channel does it print?
Ok
First of all lets clean up the code
voice_client = await channel.connect()
Then just print(voice_client)
Also keep the last print
Did you use the leave command right after?
and when i do -leave, it claims its not in a vc
and i get this:
<discord.voice_client.VoiceClient object at 0x7f181e8e3460>
<discord.voice_client.VoiceClient object at 0x7f181e8e3460>
which is what its supposed to print when its not in a vc
Huh? It prints that when it's not in a VC? I'm sorry but your sorta confusing me
@client.command()
async def leave(ctx):
voice_client = ctx.message.guild.voice_client
print(voice_client)
if voice_client.is_connected():
await voice_client.disconnect()
print('disconnected')
else:
print(voice_client)
await ctx.send('I am not connected to a voice channel')```
So when its actually connected to a vc, and i do -leave, its supposed to print voice_client and disconnected
like it did here
When i was trying on normal voice chats
#join message
@client.event
async def on_member_join(member):
embed = discord.Embed(title=f"{member} welcome to Ace Scrims!", description="Please ping either owner or staff to duel them and find out your 1v1 and 2v2 ping.", colour=0xFF0000)
embed.set_thumbnail(url=member.avatar.url)
channel = client.get_channel(914825862573064222)
await channel.send(embed=embed)
but when i tried it on the buggy voice chat, it just printed:
<discord.voice_client.VoiceClient object at 0x7f181e8e3460>```
which is the else statement in the command^
So that would probably mean your join command is bugging out perhaps
yep
It couldn't create the connection in channel.connect
but only in 1 voice channel, so weird
can anyone help
possibly
Does this voice channel have any permissions?
I gave the bot all the permissions. I then gave all the roles the bot had all the permissions for the vc
still not working
The only thing different here
in this vc is that the role 'member' cannot speak
but the bot doesnt even have that role
Have you restarted the bot at all
a couple times yes
yo whats the correct syntax for this statement role_ids = discord.utils.get(payload.guild.roles, name="Verified")
the thing is, once i ask the bot to join the buggy vc, it stops working afterwards
like every command is working, but the join command just stops working
even when u try in a different vc
that's weird, what happens if you make a new VC with the same permissions as the buggy voice channel?
Does it also hang or
Tried in the buggy vc again:
Get this:
<coroutine object Connectable.connect at 0x7f28d42a5240>
Im here
but this comes up in terminal when the bot leaves
lemme try
doesnt hang
made a copy of that buggy vc, bot works fine in the copy
so its not discord perms
Btw, i also get this when i shut my bot off after joining the buggy voicechat:
^CTask exception was never retrieved
future: <Task finished name='Task-81' coro=<VoiceClient.poll_voice_ws() done, defined at /home/lol/miniconda3/lib/python3.9/site-packages/discord/voice_client.py:410> exception=AttributeError("'NoneType' object has no attribute 'poll_event'")>
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/voice_client.py", line 414, in poll_voice_ws
await self.ws.poll_event()
AttributeError: 'NoneType' object has no attribute 'poll_event'
@pliant gulch
Probably because somewhere your bot has a connection open to a voice channel
I guess for now just use the copy of the vc instead of the real vc
This is just a weird issue overall, but right now this seems like the best workaround
true
What does this error even mean?
Well, as a discord API maintainer this I can answer
Basically Voice works by a websocket connection, same as the gateway which you receive events from
umhmm
If you don't close the websocket gracefully the websocket for the voice will try to read the events
ahh
When infact the websocket is already closed
discord.py may vary but that's how I'd do it in my wrapper
Although I'm not much of an expert on voice stuff
All I know is how the connection is made via websocket
ahh okay
also,
any clue on why this is not working?
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
audio_source = discord.FFmpegPCMAudio('file.mp3')
def play_next(*args):
voice_client.play(audio_source, after = play_next)
await asyncio.sleep(30)
voice_client.play(audio_source, after = play_next)
Basically creates a loop and has a timeout of 30 seconds between each run, but it just loop
I don't think you should do the loop like this
I have an embed, but I only want to copy specifically content of this,like 1 field or 2, which is the function? pelea se send documentation if U can, I have the event which is @bot.event
while True:
if voice_client.is_playing():
continue
else:
voice_client.play(...)
``` then just break out afterwards
I created a while loop, but that didnt work either
Lmao, has been on for more than 12 hours
Oo, lemme try
someone can try to help me pls, im needing it pls
the thing about this is:
that spams terminal lol
oh boy
with what
As for your issue, its likely because voiceclient.play spawns a thread, it won't block till the audio is finished playing
That's what the after callable is for
That should work. Although I would recommend creating a system based on the after callable instead
this is what someone else said before with while loop:
first error:
/home/lol/dsrp.py:59: RuntimeWarning: coroutine 'sleep' was never awaited
asyncio.sleep(10)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
after the voiceclip has ended: this gets sopammed:
You forgot to await
something spams my terminal really fast after the voiceclips ends
like 1000 threads in 5 seconds
at a point where i cant even stop it
Exception in voice thread Thread-4
Traceback (most recent call last):
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/player.py", line 603, in run
self._do_run()
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/player.py", line 590, in _do_run
data = self.source.read()
File "/home/lol/miniconda3/lib/python3.9/site-packages/discord/player.py", line 228, in read
ret = self._stdout.read(OpusEncoder.FRAME_SIZE)
AttributeError: 'NoneType' object has no attribute 'read'
This gets spammed
@pliant gulch
@client.command()
@commands.has_permissions(manage_messages=True)
async def welcome(ctx):
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(client.voice_clients, guild = guild)
audio_source = discord.FFmpegPCMAudio('file.mp3')
while True:
if voice_client.is_playing():
continue
else:
voice_client.play(audio_source, after = None)
await asyncio.sleep(10)
the bot plays the audio once, but then just spams the error
Put the discord.FFMpegPCMAudio inside of the loop
Works, but i get this after every play:
Error while decoding stream #0:0: Invalid data found when processing input
FFMpeg error, I'd refer to google for this one as I'm not to sure other than perhaps setting some sort of flag on your FFMpeg
class JDBotContext(commands.Context):
async def send(self, *args, **kwargs):
msg = await super().send(*args, **kwargs)
view = kwargs.get("view")
if view is not None:
view.message = msg
return msg
so I load the custom context
async def get_context(self, message, *, cls=JDBotContext):
return await super().get_context(message, cls=cls)
@commands.Cog.listener()
async def on_message_edit(self, before, after):
await self.bot.process_commands(after)
I am looking for a way to be able to edit the message, so when a user edits their message, it will rerun the context ๐ค and not have a new line.
I have a speacil dictionary to help with this anyone got any idea?
Perhaps make your JDBotContext class make a copy of message from get_context, set to a var such as previous etc. Then in your on_message_edit call await previous.delete perhaps?
Err I mean process_commands not on_message_edit
OH WAIT, ignore me this won't work
Hmmm, perhaps storing the message in a dict which the bot can access and referencing that from the on_message_edit to delete it
the problem I have to deal with multiple ctx.send calls
from the same command
๐ค with the same base context/message.id
Just capture all the Message objects from ctx.send to a list in the dict where the ID is the key of the original message
Then check in on_message_edit for after.id in the dict
๐ค I know that but I am not sure where and how I would edit every one of the ctx.sends?
or the messages?
Aren't you trying to process the command again but delete the old responses? The process_commands in on_message_edit would call the sends in your command
๐ค no I want to edit my old responses to the new ones
Then why process_commands here? Just access the message dict and iterate through all the messages stored before hand and call edit
cause it's rerunning the context....
it's invoking it again, but properly
Yes I know but that would send the messages again
I know.
But it wouldn't let me properly rexecute the commands
Perhaps the easy way to do what you want is to split your command up into another method as well, the method which determines what to send without actually sending? E.g making the content of the message, and or the embed. Then just call it from on_message_edit when it gets dispatched
Then you would get the content, etc whatever you wanted to edit the messages with
Although you might have to do some parsing with the message since you don't get context inside of on_message_edit
๐ค you can grab the context easily
await bot.get_context(msg)
Oh right yes, in this case you can do that
I was thinking of just a raw message as I had a wrong picture
?
๐ค I am not sure how I would rerun the command though
I would need to make sure to edit them, but the actual commands use ctx.send
or ctx.reply somtimes
If you reran the command it would send the messages again but you want to edit the old messages. If you split the command to have a method which makes the contents or the embed for the message you can just call that method with whatever args kwargs it needs to formulate a response, then use the return of that method to edit your messages
the problem is the complexlitly of messages too
for example if someone does an error but edits it, and gets more responses
then there's more messages to edit
I don't think complexity matters here, just migrate the code inside of the command that does the messages to a new method and handle it all in there. You just need to pass ctx.args or ctx.kwargs into this method for the args given to the command
Splitting up the method doesn't change the code just allows you to edit old responses without re-running the command fully
Your only running the specific part that makes the responses, not the part that sends them
๐ค it kind of needs to go through the command again
Ok?? ```py
#in command
response = create_responses(args, kwargs)
#send responses here
Again
If you migrate your important code, i.e not the sending parts to this other method
Is there a way to make the discord bot respond faster?
One of the events deletes messages if the message contains something explicit
But if one spams the text channel and lets say sends 50 messages at once, the bot takes a while to get rid of all the messages
do you use bulk delete with proper checks ๐ค ?
A.k.a permission checks and well checking to only delete their message
oo, i delete each separate message. let me show you the code:
this is a piece right here for example:
@client.listen()
async def on_message(message):
if message.channel.id == 912962953484066867:
if not message.author.bot:
guild = client.get_guild(904489036582879262)
manager = discord.utils.get(guild.roles, name="Session Manager")
if not manager in message.author.roles:
error = 'https://tenor.com/view/error-computer-warning-gif-8680016'
dm = await message.author.create_dm()
await dm.send(error)
await dm.send('**__Hello! Please do not talk in the notification channel! :)__**')
await message.delete()
1 thing i can do is get rid of creating a dm and just do member.send()
will that make the thing faster?
hey how do i dm message author with discord.py
using ctx?
ctx.author.send
tried that
@light night Will just doing member.send instead of creating a dm make it faster?
you can check if the dm channel exists, but you can probaly remove it
I wouldn't be sure though
await create_dm()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`DMChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.DMChannel "discord.DMChannel") with this user.
This should be rarely called, as this is done transparently for most people.
RuntimeWarning: coroutine 'Messageable.send' was never
awaited
ctx.send('Check Your Dms!')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\hoosi\Desktop\ArrowBots\STWShop_Bot\main.py:75: RuntimeWarning: coroutine 'Messageable.send' was never
awaited
ctx.author.send('test')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
if someone spams and sends 50 messages at once, the bot does it one by one and can take a few seconds. No way of making it delete messages faster?
should rarely be called
oh i never read mb
coroutine
forgot await
y'all mind if I send the link to my bot? or is it against the rules

