#discord-bots

1 messages ยท Page 734 of 1

potent spear
#

right

exotic kite
#

then tell-

maiden fable
#

Dude, you cannot go around telling people to google things. There is a reason they come here for help

potent spear
# exotic kite then tell-

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

exotic kite
#

ill learn okay jesus christ

potent spear
exotic kite
#

im better not asking help from you

slate swan
maiden fable
potent spear
#

there you have it

near sedge
#

why fight

#

fight = bad

potent spear
#

he's just stubborn

maiden fable
junior verge
#

Anyone?

maiden fable
junior verge
#

Oh.

near sedge
maiden fable
#

Tho the question will better be suited in #databases

near sedge
#

i asked and got ghosted ๐Ÿ’€

maiden fable
#

Ouch

potent spear
#

use an async wrapper asap

#

if you know basic CRUD operations, you'll get far

maiden fable
potent spear
#

it'll save him time in the long run

maiden fable
#

Not much advantage by using motor since its just pymongo with asyncio

near sedge
#

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

maiden fable
#

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

potent spear
#

only the id is enough

maiden fable
#

And yea, that too

potent spear
#

userTags can change overtime

near sedge
#

then with balance it just stopped

maiden fable
#

u got an error handler?

near sedge
#

nope the bot just doesn't output anything

maiden fable
#

hmm

#

Sorry bruv, I haven't used PyMongo that much... Try asking in #databases

potent spear
#

can you show us the insert that DOES work?

near sedge
#

sure

#
profile = {
            "userId":ctx.message.author.id,
            "userTag":ctx.message.author
        }
collection.insert(profile)
potent spear
#

where do you get your info from? which site?

maiden fable
#

he is making an economy bot

near sedge
potent spear
near sedge
#

but documentation info i got it from the docs and this guy on youtube called techwithtim

maiden fable
#

Ah

#

U using MongoDB Atlas?

near sedge
#

i haven't really messed around with databases that much so its quite new to me

near sedge
slate swan
#

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

maiden fable
unkempt canyonBOT
#

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.
potent spear
#

the docs I see, are only using insert_one or insert_many
idk where he gets the insert from

maiden fable
#

yea, that is what I was also seeing ngl

near sedge
#

its worked with both

maiden fable
#

could be a shortcut method

slate swan
#
@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

maiden fable
#

u do message.content.lower()

slate swan
slate swan
potent spear
#

the if statement can also be shorted
if any(list comprehension here):

maiden fable
#

Yea that too

slate swan
#

if any(badword) in message.content.lower():?

potent spear
#

no

maiden fable
#

no

#

any([word for word in badwords if word in message.content.lower()])

slate swan
#

do slash commands consume more memory than normal commands?

potent spear
#

also, censoring can be nice, but users will always be smarter

maiden fable
lament mesa
potent spear
maiden fable
slate swan
maiden fable
#

do u have messages intent?

lament mesa
slate swan
potent spear
slate swan
#

i meant to say messages intents... im just sick af sorry

maiden fable
#

mind showing your intents?

slate swan
maiden fable
#

ah

potent spear
#

boom

maiden fable
#

that's the issue

#

use @bot.listen("on_message") and then name your functions something else

slate swan
#
@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

maiden fable
#

also remove the await bot.process_commands after doing this

slate swan
potent spear
#

you're a smart guy

maiden fable
#

Sure he is

slate swan
#

yayy

#

it worked

maiden fable
#

Cool!

slate swan
#

thank you all guys

maiden fable
#

Also @slate swan

manic wing
slate swan
#

yes?

maiden fable
#

Prevent using @bot.event. Prefer using @bot.listen() since the bugs are lesser with it

potent spear
#

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

slate swan
#

@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

maiden fable
#

members intent

#

!intents

unkempt canyonBOT
#

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.

slate swan
potent spear
#

you don't

maiden fable
#

in code also?

slate swan
#

yes

potent spear
#

you don't

#

impossible

slate swan
#

intents=discord.Intents.all()

potent spear
#

and now in the bot constructor too?

slate swan
#

you mean in the developer portal?

potent spear
#

commands.Bot(....., intents = intents)

slate swan
#

i am trying this

#

wait a sec

potent spear
#

It'll work, ofc

slate swan
#

still nothing

potent spear
#

code?

#

intents + bot constructor + discord portal

slate swan
#
from discord import Intents


intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix = '!', help_command=None, case_insensitive=True, intents=intents)
potent spear
#

cool, and now the discord portal

slate swan
potent spear
#

restart the bot and it'll work

slate swan
#

nothing

potent spear
#

you don't have 2 bot instances, do you?

potent spear
#

hmm

#

!paste

unkempt canyonBOT
#

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.

potent spear
#

do that, don't leak token

potent spear
maiden fable
#

You most probably have another function named on_member_join

slate swan
#

yes it is xD

potent spear
#

my god

maiden fable
#

(: that is the issue

potent spear
#

I thought he learned his lesson after the on_message lol

maiden fable
#

You are shadowing functions

slate swan
#

i didnt know you were not able to do the same event twice, i just dont like messing my code up lol

potent spear
#

just organize one function, you can put it all in one
having a lot of small functions can be quite useless too sometimes

maiden fable
#

He is such a gentleman

slate swan
#

well i am not so stupid i promise

#

thanks, i learnt the lesson now

maiden fable
#

Its fine haha

potent spear
#

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

polar ice
#

Ive made my own function, is it possible to get the guild_id?

manic wing
#

wot

maiden fable
#

sure

#

u can simply do guild.id where guild is an instance of discord.Guild

polar ice
#
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

manic wing
#

and you thing he understands that? xD

polar ice
#

Prints None ๐Ÿ˜„

manic wing
#

means you didnt pass anything

#

global ๐Ÿ˜ข

maiden fable
potent spear
maiden fable
#

but if u wanna make linters happy, then u will have to subclass the bot class haha

polar ice
#

@potent spear Im hoping to get it into a couple of guilds. my first time trying it ๐Ÿ™‚

manic wing
potent spear
polar ice
#

Im trying to get it to compare it to a database to retrieve all the server information ๐Ÿ™‚

potent spear
#

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

polar ice
#

for example

potent spear
#

the guild name etc can be edited, no need to store that

#

guild ID is all you need

#

in the GUILDS table

polar ice
#

Any idea how i can get the guild id from what i have above? ๐Ÿ™‚

potent spear
#

tell us what you're trying and we'll simplify it for you

polar ice
#

@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

potent spear
#

you're a smart guy with some coding background, am I correct?

#

like a bit of SQL, not too much python

polar ice
#

Little ๐Ÿคฃ my first time trying to make a bot which can hopefully go into a few guils

potent spear
#

well, have you ever used commands before?

polar ice
#

commands?

potent spear
#

this is an example of a command

#

!paste

unkempt canyonBOT
#

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.

potent spear
#

see what the bot did? based on the command, it responded with a message

polar ice
#

yeah ive made commands ๐Ÿ˜„

potent spear
#

alright, is your db implemented in your bot already?

polar ice
#

Yeah it is, but i can easily change it

potent spear
#

what library are you using?

polar ice
potent spear
#

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?

polar ice
#

Yes sir!

potent spear
#

excellent

#

alright, so your DB structure should have 2 tables

polar ice
potent spear
#

3 tables actually

#

guilds, members and userstats

polar ice
#

okay?

potent spear
#

guilds has guildID
members has user ID

#

and userstats has guildID userID kills, etc etc

kindred drum
#

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)


        ```
potent spear
#

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

polar ice
#

๐Ÿ‘€ gotcha

potent spear
#

userstats table can have columns with the same memberID, but a different guildID, you see?
the same user has different stats on different guilds

potent spear
polar ice
#

๐Ÿ˜ฎ ahh ofcourse

potent spear
#

you just need a good DB structure and you're all set

polar ice
#

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

kindred drum
#

and I don't think I can

polar ice
#

guild_id,admin_id, any server settings

potent spear
polar ice
#

then all the player info

potent spear
polar ice
#

Gotcha ๐Ÿ™‚ ill have a play

#

Appreciate the advice

#

Going to re-strcuture now

potent spear
#

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

polar ice
#

Do you have any idea why it wasn't retrieving the guild id from the code i sent above? just for future reference

potent spear
polar ice
#
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

potent spear
#

and now show me where you use it

#

also, don't use global variables here

polar ice
#

!paste

unkempt canyonBOT
#

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.

polar ice
#

be easier if i show you the whole function?

potent spear
#

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

polar ice
#

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 ๐Ÿ™‚

potent spear
#

you're a smart guy

#

you see line 30, right? in the paste url

polar ice
#

yeah

potent spear
#

put this above it and give me the output

print(f"{guild_id}, {type(guild_id)}")
polar ice
#

hey sorry back:)

#

@potent spear Its 0 and a Int

quaint epoch
#

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

potent spear
quaint epoch
slate swan
#

then what happened

quaint epoch
#

it just kept saying that TypeError

slate swan
#

post the error if there's any

slate swan
quaint epoch
#

that type object cannot be iterated over

polar ice
#

@potent spearNo, exactly ๐Ÿ˜„

potent spear
median gale
#

are we allowed to send links to our bots here?

quaint epoch
quaint epoch
median gale
#

i made a bot that gets reddit memes, weather, math from wolfram alpha, advice, jokes and stuff

tidal hawk
#

Coool

tidal hawk
quaint epoch
median gale
#

ok

#

type ?help to get started

quaint epoch
#

wait

median gale
#

sup

final iron
#

Not the right channel

#

Or Discord server for that fact

median gale
#

oh

slate swan
#

advertising your bot really?

median gale
#

thats not allowed?

#

im tryna get feedback

slate swan
#

no

median gale
#

oh ill delete it

slate swan
#

show your code we can feedback on that

median gale
#

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

slate swan
#

nah i didnt knew that seems cool

boreal ravine
#

ot but I'm thinking of making a chair API

final iron
#

They have a ton of public api's

#

I'm going to implement some

boreal ravine
#

F

potent spear
#

I don't like useless API's that much ๐Ÿ™‚

stray thistle
#

does anyone use repl.it ? Idk how to import a fork like disnake

final iron
#

import disnake

boreal ravine
#

install it in the package manager/shell

slate swan
potent spear
median gale
slate swan
stray thistle
stray thistle
slate swan
boreal ravine
final iron
stray thistle
#

Oh Iโ€™ll check then

median gale
#

any good free apis u guys know of?

boreal ravine
#

theres a button called shell and theres a button for the package manager

median gale
slate swan
stray thistle
slate swan
boreal ravine
slate swan
#

oke thx

potent spear
slate swan
boreal ravine
#

Do ?tag apis in the dpy server for more apis lol

potent spear
slate swan
final iron
#

I got a lot of work to do now

#

Thats a shit ton of api's

slate swan
#

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)?

hoary palm
#

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)

slate swan
# slate swan

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?

unkempt canyonBOT
magic stump
#
    await ctx.channel.set_permissions(ctx.author)``` hello how can i change permission that ctx author can read this and write
spring flax
#

How does one get the message intents?

crude orchid
#

How to start coding with python ? pydis_peek (yes new )

magic stump
slate swan
#

is there any package i can use for the discord.py buttons?

magic stump
spring flax
magic stump
#

idk

vivid patio
#

check Pins for more information

slate swan
slate swan
slate swan
unkempt canyonBOT
slate swan
#

thanks!

#

yw

fringe harness
slate swan
fringe harness
#

ur choice

slate swan
#

for what exactly?

fringe harness
#

just to clear up confusion from the past

slate swan
#
@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!")
slate swan
quick gust
crude orchid
magic stump
#
    await ctx.channel.set_permissions(ctx.author)``` hello how can i change permission that ctx author can read this and write
slate swan
slate swan
slate swan
quick gust
slate swan
#

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

slate swan
crude orchid
manic wing
#

theres no such thing as a tempbot

crude orchid
quick gust
vivid patio
slate swan
boreal ravine
slate swan
slate swan
boreal ravine
#

Invisible characters

crude orchid
#

Just let me try to code on android if that is possible ๐Ÿ˜ถ

boreal ravine
#

Oof

boreal ravine
slate swan
#

@quick gust tried also this response = await bot.wait_for("button_click")

final iron
slate swan
slate swan
slate swan
# vivid patio mind sharing few reasons?
  • 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.

boreal ravine
quick gust
slate swan
#

There's no substitute for a cursor and a keyboard. Coding on a phone just feels uncomfortable.

slate swan
lost lagoon
#

hello

slate swan
#

i learnt how to make some with that package

lost lagoon
quick gust
#

!d discord.ui.Button

unkempt canyonBOT
#

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.
slate swan
final iron
crude orchid
#

So which app to use for coding (until buys laptop ๐Ÿฅฒ )

random kelp
#
@commands.command()
async def eee(ctx,user : discord.Member,*,role: discord.Role):
    await user.add_roles(role)
boreal ravine
slate swan
slate swan
random kelp
#

discord.ext.commands.errors.CommandNotFound: Command "eee" is not found

slate swan
vivid patio
boreal ravine
random kelp
#

waittt

crude orchid
spring flax
#

perm_list = member.permissions_in(channel)
raises
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'permissions_in'

boreal ravine
spring flax
#

Has it been removed or something? I know it was there before

unkempt canyonBOT
#

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...
spring flax
#

what happened to permissions_in?

boreal ravine
#

it returns the members permissions in the channel

magic stump
#

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)```
boreal ravine
random kelp
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

random kelp
#

huh

#

what perm

boreal ravine
#

@spring flax removed

final iron
#

Check the docs for whatever you're trying to do

random kelp
#

he has admin

boreal ravine
random kelp
#

ya

#

thats the point

boreal ravine
#

yes?

random kelp
#

i think so

spring flax
#

how do I get the permissions which are True?

boreal ravine
spring flax
#

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

boreal ravine
boreal ravine
#

It should work

spring flax
boreal ravine
#

hm

#

@spring flax ah

#

you gotta index perm

boreal ravine
random kelp
boreal ravine
random kelp
#

huh are you sure

boreal ravine
#

yes..?

spring flax
#

ah thanks

boreal ravine
#

๐Ÿ‘

slate swan
#

Unless you are a Discord engineer and edit the code of their API you can't change it bravemmlol

magic stump
#

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)```
kindred drum
#

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

pallid marsh
#
@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.
pliant gulch
#

You need member intents in order to receive member_join from the gateway

#

!intents

unkempt canyonBOT
#

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.

pallid marsh
#

i have them enabled in both the dev portal and the code

pliant gulch
#

Can you show your client's constructor

pallid marsh
#

wdym

pliant gulch
#

Show the code where you construct the client

kindred drum
#

=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

pallid marsh
#
intents.members = True``` this is what i have for the intents
pliant gulch
#

Yea, but show the client's constructor.. The Client(...) or the commands.Bot(...)

pallid marsh
#

this? client = discord.Client(activity=discord.Activity(type=discord.ActivityType.watching, name="for $help"))

pliant gulch
#

Yes

#

And that's your issue

#

You never pass intents to your clients constructor

pallid marsh
#

ohh i didnโ€™t know you needed to do that

#

where do i pass it in

pliant gulch
#

In the constructor

#

It's a kwarg

#

!d discord.Client

unkempt canyonBOT
#

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").
pallid marsh
#

is there a certain spot it has to go

pliant gulch
frail notch
#

How can I make this into a command for my discord bot?
So essentially I want it to go: >id SERVER_ID CHANNEL_ID

pliant gulch
#

It's the same name as what you called the variable

pliant gulch
frail notch
#

me?

pliant gulch
#

No

frail notch
#

lol

pliant gulch
#

And your code seems to suggest you are selfbotting ๐Ÿค”

#

This server doesn't help with selfbots

frail notch
#

i mean im tryna put it into a bot

pliant gulch
#

Then why are you using discum and not a regular wrapper?

frail notch
#

idk its a code i got from github

pliant gulch
#

๐Ÿค”

cold sonnet
#

WHAT IS THAT NAME

pallid marsh
#

ah ok thanks @pliant gulch

pliant gulch
frail notch
#

whats a patched wrapper ๐Ÿ˜‚

pliant gulch
#

A wrapper specifically made to make selfbots work again

#

If your making a regular bot. Use a regular wrapper

kindred drum
#

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

frail notch
#

thx

#

now time to learn to code in python ig... aka learn to do something else then print("hello")

unkempt canyonBOT
kindred drum
frail notch
#

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)

cold sonnet
slate swan
#

how can i host my own discord bot? i bought vps but what next?

kindred drum
frail notch
pliant gulch
#

The VPS might not keep alive though, if you on linux you can just use screen

slate swan
pliant gulch
#

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

slate swan
#

thanks

#

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

Anyone know what this means?

pliant gulch
#

You forgot to await a coroutine

kindred drum
#

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?

slate swan
#

[apt --fix-broken install] why its dosent work?

slate swan
#

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.

surreal sierra
#

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}")
slate swan
#

Then you can go for embed.fields[index].name

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

d
surreal sierra
kindred drum
#

its a dictonary

unkempt canyonBOT
#

@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!

slate swan
#

Replace json with your variable

#

!e
x = {
"fields": [
{
"name": "ID"
}
]
}

print(x["fields"][0]["name"])

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

ID
slate swan
#

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?

meager chasm
#

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

slate swan
#

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?

meager chasm
#

That should work. Although I would recommend creating a system based on the after callable instead

slate swan
#

wdym a system?

meager chasm
#

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
slate swan
meager chasm
#

You won't need a timeout

slate swan
#

Well i want 10 seconds before the audio. repeats lol

meager chasm
#

Oh

slate swan
#

yea

meager chasm
#

That's fine then

#

You can call time.sleep in the after callable if you need a delay

slate swan
#

What im looking at is:

def play_next(*args):
       ...

while True:
    play_next()
    ayncio.sleep(10)
#

nvm okay

meager chasm
#

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

slate swan
meager chasm
#

It's kinda recursive

#

the function itself is passed to voiceclient.play in itself

slate swan
#

oo

meager chasm
#

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

slate swan
#

so: the after plays the file again

#

umhmm

meager chasm
#

Yep

slate swan
#

perfecto

#

lemme try

green bluff
#

join / leave msg pls

#

do i do on_member_join?

slate swan
#

nvm it started playing after 30 seconds

#

but

slate swan
#

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.

green bluff
#

@slate swan where r u hosted on bro u have like 24/7 help

#

yea sure

slate swan
#

x)

#

I simply like to help :)

green bluff
#

its client.event() right @slate swan

slate swan
#

No (), other than that it's correct.

green bluff
#

@slate swan sorry a second

slate swan
# meager chasm Could you send the code
@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

meager chasm
#

That's weird

green bluff
#

@slate swan what do i do next

slate swan
#

Print the member argument, that's will be the member who joined the guild.

slate swan
#

would that work?

dapper cobalt
#

Happy birthday, @slate swan! ia_love Birthday_Cake

slate swan
#

Can I take my day off from helping now? KryptonBlanket

meager chasm
slate swan
slate swan
#

it doesnt even join the channel anymore]=

#

lemme reset it

#

AttributeError: 'NoneType' object has no attribute 'poll_event'

meager chasm
#

Full traceback please

#

Is the bot in a vc?

slate swan
#

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'
green bluff
#

@slate swan sorry can u explain it further

meager chasm
green bluff
#

client.event

ebon island
#

Is there a way to get a list of aliases bound to the commands on a serveR?

green bluff
#

async def on_member_join?

slate swan
#
@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
frail notch
#

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?

slate swan
green bluff
#

yup then

slate swan
green bluff
#

get_channel_id channel.send('welcome')

#

there?

slate swan
#

For that you'd need to use get_channel

frail notch
slate swan
#

!d discord.Guild.get_channel

green bluff
#

yes i did

unkempt canyonBOT
#

get_channel(channel_id, /)```
Returns a channel with the given ID.

Note

This does *not* search for threads.
slate swan
#

Then you can send, yep

slate swan
kindred drum
#

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

frail notch
meager chasm
slate swan
green bluff
#

pylance cant access

frail notch
green bluff
#

member @slate swan

ebon island
#

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

slate swan
green bluff
#

proabbly cause i have to use member

slate swan
#

Now you can continue by enabling intents and then you're done.

slate swan
kindred drum
slate swan
#

You'd need an oauth connection to be able to join a server, so via a website for example.

slate swan
unkempt canyonBOT
frail notch
green bluff
#

@slate swan would this work

slate swan
#

await when sending, then yes.

green bluff
slate swan
#

Yep - now you'll need to enable intents

green bluff
#

intents?

slate swan
#

Go to your developer dashboard, click on your application and to the left click on "Bot"

kindred drum
slate swan
#

Then enable the "Server Members Privileged Intent"

frail notch
slate swan
hushed rain
#

I need help saving discord request.get and printing it in a payload to send text to discord. Can anyone help?

slate swan
#

Don't use the requests library in an async library like discord.py

frail notch
#

oh

#

alr

green bluff
slate swan
#

Then enable the members privileged intent shown

dire folio
#

is there a limit on how old a message can be to edit it

green bluff
#

done

green bluff
#

now will it work

slate swan
#

!intents

unkempt canyonBOT
#

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.

slate swan
#

See the code part, you also need that.

meager chasm
#

97 days

dire folio
# slate swan No

weird cause i tried editing a msg and it said message not found

#

but when i try with a different one it works

hushed rain
#

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

green bluff
#

done @slate swan

#

would it work

unkempt canyonBOT
#

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.

slate swan
#

You can try it out

hushed rain
#
# 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)
    
meager chasm
slate swan
#

So the bot apparently doesn't have permissions to send in these channels?

hushed rain
#

I want to link the two

#

the Retrieve messages and the send messages

#

to send a message when it receives one

green bluff
#

nothing @slate swan

#

the bot said nothing

slate swan
slate swan
green bluff
#

!code

unkempt canyonBOT
#

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.

slate swan
#

Especially when you define client

slate swan
green bluff
#

client = commands.Bot(command_prefix='!')

#

here

slate swan
#

You're missing the intents part

meager chasm
green bluff
#

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.')

slate swan
#
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.

unkempt canyonBOT
#

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!

green bluff
#

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')

Discord Developer Portal

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

slate swan
#

Enable the one at the bottom

green bluff
#

oops enabled presence intent

#

thanks it worked

#

same thing for leave except on_member_leave right

#

@slate swan

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.

pliant gulch
#

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

slate swan
pliant gulch
#

Help with what

slate swan
#

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.
kindred drum
#
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
pliant gulch
#

Can you show your code again rq

slate swan
#

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()
pliant gulch
#

Probably because this maybe doesn't gracefully close the websocket which is keeping VoiceClient alive

slate swan
#
@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')
pliant gulch
#

Well can I see the part where it is playing the audio?

slate swan
#

I havent even played the audio yet

slate swan
#

It doesnt even properly join the channel yet

#

this is the second part

pliant gulch
#

So your bot for some reason thinks it isn't connected to a voice channel, but once it connects it is actually connected already?

slate swan
#

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

pliant gulch
#

For every voice channel other than the buggy one also joining and leaving?

slate swan
#

nop

#

Just the buggy 1 joining leaving

#

Every other its working fine

pliant gulch
#

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

slate swan
#

oo

kindred drum
#
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
slate swan
#
@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)
pliant gulch
slate swan
#

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

pliant gulch
#

Can you print the voice_client var?

slate swan
#

Lemme try

pliant gulch
#

Not from the welcome command btw

#

from the leave one

hushed rain
#

how to I find more information on discord.py and how to use it

hushed rain
final iron
hushed rain
final iron
#

Also, I would suggest you get started with a fork instead of dpy because development and maintenance on it has stopped

final iron
#

I would personally recommend disnake but peoples opinions differ

severe rampart
#

i use disnake

final iron
#

!pypi disnake

unkempt canyonBOT
proven ore
#

yeah or pycord

#

!pypi py-cord

unkempt canyonBOT
proven ore
#

!pypi pycord

unkempt canyonBOT
proven ore
slate swan
#
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

pliant gulch
slate swan
#

The bot like joins, leaves, joins, leaves so fast =. its for like a split second, do you think its glitching itself out?

pliant gulch
#

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

slate swan
#

ummm

#

What steps will fix this ?

#

Should i add another check that makes sure its in the voicechat?

pliant gulch
#

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

unkempt canyonBOT
#

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.
hushed rain
#

Does someone want to hop on a voice call and help a buddy and I with a discord scrapper?

slate swan
#

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

pliant gulch
#

Can you set a var to channel.connect() and print that as well?

#

Since that will return the VoiceClient

slate swan
#

yep

pliant gulch
#

Also maybe the channel has permissions that stop your bot from joining?

slate swan
#
<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

pliant gulch
#

You didn't await the connect from what the error is saying

slate swan
#

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

pliant gulch
#

And if you remove the connect call when in the buggy channel does it print?

slate swan
#

i got something

#

<coroutine object Connectable.connect at 0x7f181d7a14c0>
Im here

pliant gulch
#

Ok

#

First of all lets clean up the code

#

voice_client = await channel.connect()

#

Then just print(voice_client)

#

Also keep the last print

slate swan
#

but its not in the vc anymore

#

like its not physically here

pliant gulch
#

Did you use the leave command right after?

slate swan
#

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

pliant gulch
#

Huh? It prints that when it's not in a VC? I'm sorry but your sorta confusing me

slate swan
#
@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

green bluff
slate swan
#

When i was trying on normal voice chats

green bluff
#

#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)

slate swan
#

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^

pliant gulch
#

So that would probably mean your join command is bugging out perhaps

pliant gulch
#

It couldn't create the connection in channel.connect

slate swan
#

but only in 1 voice channel, so weird

green bluff
#

can anyone help

pliant gulch
#

Does this voice channel have any permissions?

slate swan
#

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

pliant gulch
#

Have you restarted the bot at all

slate swan
#

a couple times yes

kindred drum
#

yo whats the correct syntax for this statement role_ids = discord.utils.get(payload.guild.roles, name="Verified")

slate swan
#

like every command is working, but the join command just stops working

#

even when u try in a different vc

pliant gulch
#

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

slate swan
#

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

slate swan
#

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

pliant gulch
#

Probably because somewhere your bot has a connection open to a voice channel

pliant gulch
#

This is just a weird issue overall, but right now this seems like the best workaround

slate swan
pliant gulch
#

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

slate swan
#

umhmm

pliant gulch
#

If you don't close the websocket gracefully the websocket for the voice will try to read the events

slate swan
#

ahh

pliant gulch
#

discord.py may vary but that's how I'd do it in my wrapper

slate swan
#

ummm

#

interesting

pliant gulch
#

Although I'm not much of an expert on voice stuff

#

All I know is how the connection is made via websocket

slate swan
#

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

pliant gulch
#

I don't think you should do the loop like this

coral schooner
#

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

pliant gulch
slate swan
heavy radish
#

Lmao, has been on for more than 12 hours

coral schooner
slate swan
slate swan
#

oh boy

pliant gulch
#

with what

slate swan
#
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:

pliant gulch
#

You forgot to await

slate swan
#

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

pliant gulch
slate swan
pliant gulch
#

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

light night
#
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?

pliant gulch
#

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

light night
#

the problem I have to deal with multiple ctx.send calls
from the same command
๐Ÿค” with the same base context/message.id

pliant gulch
#

Then check in on_message_edit for after.id in the dict

light night
#

๐Ÿค” I know that but I am not sure where and how I would edit every one of the ctx.sends?
or the messages?

pliant gulch
#

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

light night
pliant gulch
#

Then why process_commands here? Just access the message dict and iterate through all the messages stored before hand and call edit

light night
pliant gulch
#

Yes I know but that would send the messages again

light night
#

I know.
But it wouldn't let me properly rexecute the commands

pliant gulch
#

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

light night
#

๐Ÿค” you can grab the context easily
await bot.get_context(msg)

pliant gulch
#

Oh right yes, in this case you can do that

#

I was thinking of just a raw message as I had a wrong picture

light night
#

pithink ?

pliant gulch
#

How about ctx.args or ctx.kwargs

#

Either way should be pretty easy

light night
#

๐Ÿค” 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

pliant gulch
light night
#

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

pliant gulch
#

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

light night
#

๐Ÿค” it kind of needs to go through the command again

pliant gulch
#

Ok?? ```py
#in command
response = create_responses(args, kwargs)
#send responses here

pliant gulch
#

If you migrate your important code, i.e not the sending parts to this other method

slate swan
#

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

light night
slate swan
#

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?

storm steppe
light night
#

user.send
or member.send

#

fyi
Don't dm users randomly

storm steppe
#

using ctx?

light night
#

ctx.author.send

storm steppe
slate swan
light night
heavy folio
#

!d discord.Member.create_dm

unkempt canyonBOT
#

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.
storm steppe
# heavy folio errors?

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

slate swan
#

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?

heavy folio
#

should rarely be called

storm steppe
#

oh i never read mb

storm steppe
jovial dock
#

y'all mind if I send the link to my bot? or is it against the rules