#discord-bots

1 messages ยท Page 927 of 1

inland shell
#

bc i use replit...

sick birch
#

Uh yeah that's a problem

inland shell
#

.

oblique laurel
#

Replit is trash for bots

sick birch
#

Get rid of the "for bots" part

oblique laurel
#

Lol true

supple thorn
#

Yeah i did check the docs it's just that my brain thought intents were already enabled

oblique laurel
#

The only time you should use replit is

#

Absolutely never

gaunt ice
royal wind
#

I'm gonna need help, but I'll wait if someone's still being helped

slim ibex
royal wind
#

I am using MongoDB for database. Each document will be a user's profile. It will have fields like user_xp, user_point, etc

But, not all users will have the same fields at the same time. If, say, they want to check their server points, they'd do $points. Then, it would check if the user has user_point field.

The problem is with the checking. This is my code so far, and it just won't work.

#

It would always end up with "you may only claim once a day"

#

I thought, if MongoDB do the lookup and finds nothing, it will simply return null. So I tried checking is None. It still doesn't work

inner epoch
#

Any1 knows how to use link buttons with persistent views?

inner epoch
#

Umm how?

hushed galleon
#

you just do...?

#

there shouldnt be anything special with combining url buttons and persistency

boreal ravine
#

make the view -> add the button -> make it persistent

inner epoch
#
class help_class(disnake.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    disnake.ui.button(label="Abc",url="", custom_id="help:1")

    disnake.ui.button(label="Def",url="", custom_id="help:2")
boreal ravine
unkempt canyonBOT
#

add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.

This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.

New in version 2.0.
royal wind
inner epoch
inner epoch
hushed galleon
unkempt canyonBOT
#

examples/views/link.py lines 22 to 32

class Google(discord.ui.View):
    def __init__(self, query: str):
        super().__init__()
        # we need to quote the query string to make a valid url. Discord will raise an error if it isn't valid.
        query = quote_plus(query)
        url = f'https://www.google.com/search?q={query}'

        # Link buttons cannot be made with the decorator
        # Therefore we have to manually create one.
        # We add the quoted url to the button, and add the button to the view.
        self.add_item(discord.ui.Button(label='Click Here', url=url))```
inner epoch
#

Umm let me try that one

boreal ravine
cerulean osprey
#

With @commands.has_role how do I make it do something if they dont have the role?

boreal ravine
cerulean osprey
#

So Im assuming the error would be commands.MissingRole ?

cerulean osprey
#

Gotcha ty

inner epoch
#

@hushed galleon @boreal ravine Thanks for help got it working!

#

Btw the links button are already persistent no need to make them persistent

royal wind
boreal ravine
#

Show updated code

royal wind
#

Ouch, there's exception raised

slate swan
royal wind
slate swan
inner epoch
boreal ravine
#

u dont need to check it lol

boreal ravine
slate swan
inner epoch
royal wind
#

This is so if I make new features that require fields, I won't forget adding it

inner epoch
#

Is there some way for the bot to check if it misses any permission?

slate swan
inner epoch
slate swan
#

..

unkempt canyonBOT
#

exception discord.ext.commands.BotMissingPermissions(missing_permissions, *args)```
Exception raised when the botโ€™s member lacks permissions to run a command.

This inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
vale wing
#

There are at least 3 ways but they relate to different situations

rose birch
#

hey guys, I'm having issues with the bot not running tasks in the background >< the idea is to iterate through names inside of a dictionary then make a background task for that specific item. issue is, it gets stuck on the very first item and doesn't proceed to the next

itemNames = [item1, item2, ..]
async def main():
  for item in itemNames:
    await createTask(item)

async def createTask(item):
  await bot.loop.create_task(backgroundTask(item))

async def backgroundTask(item):
  while True:
    print(item)
  await asyncio.sleep(5)

# my output: 
# item1
# item1
# ...
vale wing
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
vale wing
#

Use this for background tasks

#

Examples in docs

#

And this one gets stuck because of while True loop (why would you even want to print something forever)

rose birch
vale wing
#

Use the thing I suggested

#

The thing in the examples is not for your case

inner epoch
#

Aha got it Ill fix that with error event

inner epoch
glacial echo
#

but?

vale wing
glacial echo
#

this should pull the relevant embed for this channel?

inner epoch
vale wing
glacial echo
#

a dictionary

vale wing
glacial echo
#

theoretically in format {channelid : embed}

#
client.currentEmbed[ctx.channel.id] = await ctx.send(embed=embedVar)
vale wing
#

!d discord.ext.commands.BotMissingPermissions.missing_permissions

unkempt canyonBOT
vale wing
#

This @inner epoch

vale wing
#

send returns the message

#

Your embed is embedVar

glacial echo
#

an embed is a message type

#

ok so

vale wing
#

O nvm didn't see

glacial echo
#

i am constructing an embed, and assigning it to the embed parameter of a message

vale wing
#

Your format is channel_id: message

#

Don't confuse

glacial echo
#

then later i am trying to pull the message (which only has an embed) and change what the embed is within the message

vale wing
#

Try printing the dict

glacial echo
#

but it would appear that somehow it doesnt have an edit param

inner epoch
inner epoch
glacial echo
#

the dict has a none as the channels data

#

which is odd as before makign it construct a dict to make it channel relative, it was properly setting the value

glacial echo
vale wing
#

Um yeah

glacial echo
#

thats the channel id but obviously not the embed

vale wing
maiden fable
#

@glacial echo u completed the command yesterday?

maiden fable
#

The join party one

#

Or idk was that 2 days ago

vale wing
#

Are you sure the send isn't raising any errors

glacial echo
#

the send isnt erroring and is sending the embed in the channel

vale wing
#

Try storing message id as a value in dict and then fetch it when needed

glacial echo
#

?

#

maybe i need to pre-assign the dict key?

vale wing
#
m = await ctx.send(...)
client.current_embeds[ctx.channel.id] = m.id

...

# when the fetch
m = await client.get_channel(channel_id).fetch_message(client.current_embeds[channel_id])
await m.edit(...)```
glacial echo
#

nope

vale wing
#

And you define the client like commands.Bot right?

glacial echo
#

yes

#

client = commands.Bot

glacial echo
#

client.get_channel(channel_id) isnt a thing

#

channel_id at least isnt

maiden fable
unkempt canyonBOT
glacial echo
#

ahhhh

#

it would seem that send doesnt return anything in disnake

#

for some reason?

slate swan
glacial echo
#

one would think

#

it appears to not be doing that

slate swan
glacial echo
#

yeah i know it should but its returning a NoneType

slate swan
glacial echo
#

yes

slate swan
#

try printing the object

maiden fable
glacial echo
#

it sends a message, then fails to return that object

slate swan
maiden fable
#

Eh, what u talking about

slate swan
unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
maiden fable
#

Ah, talking about send

#

My bad

glacial echo
slate swan
maiden fable
#

ยฏ_(ใƒ„)_/ยฏ

slate swan
#

lol

slate swan
# glacial echo

disnake dies in its own world sometimes ๐Ÿ˜”
@maiden fable any help?

maiden fable
#

What

#

disnake never fucked up send method's return

slate swan
#

yeah

glacial echo
#

maybe my internet is just being shit right now?

maiden fable
#

@glacial echo mind showing code?

maiden fable
slate swan
glacial echo
#

would it be possible my internet being slow means it is moving on in the code before it actualyl gets a returned ID

glacial echo
maiden fable
#

Nah

slate swan
maiden fable
#

can I see some code?

slate swan
maiden fable
#

Don't

glacial echo
#

can i just link my github for it?

slate swan
#

yeah do that

glacial echo
maiden fable
#

Link the GitHub line

#

not the whole repo

slate swan
#

or the file url ๐Ÿ˜”

glacial echo
maiden fable
#

Also the repo is private

glacial echo
#

its private???

#

b r u h

maiden fable
slate swan
maiden fable
maiden fable
glacial echo
#

damn ig its fixed

maiden fable
#

which file

unkempt canyonBOT
#

dicord_game_bot.py line 57

async def startGame(ctx, gameID: int = 1):```
slate swan
maiden fable
#

Cz it wanna hide that the repo is private

glacial echo
#

ohhhh its private cause i created it from a local repo with github desktop

#

duh

maiden fable
#

Like, what doesn't work

glacial echo
#

so, when you send a message for the game it cant edit the embeds

maiden fable
#

Ha I got the issue

#

u r using slash commands

glacial echo
#

becasue for some reason the message object within the dict is a NoneType object and NOT a message object

slate swan
#

you made the stuff more complex than they should be

maiden fable
#

Haha u need to do ctx.original_message()

glacial echo
maiden fable
#

!d disnake.Interaction.original_message

unkempt canyonBOT
#

await original_message()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Fetches the original interaction response message associated with the interaction.

Here is a table with response types and their associated original message...
maiden fable
slate swan
#

slashes and Context wigglewiggle_pensive

#

GWcmeisterPeepoShrug why would you do this to them

slate swan
glacial echo
#

where do i do that

maiden fable
#

After ctx.send

#

In the next line: var = await ctx.original_message() replacing var with the original variable

glacial echo
#

not sure i understand ???

vale wing
#

OH LMAO THAT WAS A SLASH COMMAND

#

Name variables properly for god's sake

#

It should not be ctx, it should be something like inter

glacial echo
#

i mean?

#

idk man it worked by default so

vale wing
#

And yeah

#

!d disnake.ApplicationCommandInteraction.send

unkempt canyonBOT
#

await send(content=None, *, embed=..., embeds=..., file=..., files=..., allowed_mentions=..., view=..., components=..., tts=False, ephemeral=False, delete_after=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using either [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message") or [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").

If the interaction hasnโ€™t been responded to yet, this method will call [`response.send_message`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionResponse.send_message "disnake.InteractionResponse.send_message"). Otherwise, it will call [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send").

Note

This method does not return a [`Message`](https://docs.disnake.dev/en/latest/api.html#disnake.Message "disnake.Message") object. If you need a message object, use [`original_message()`](https://docs.disnake.dev/en/latest/api.html#disnake.ApplicationCommandInteraction.original_message "disnake.ApplicationCommandInteraction.original_message") to fetch it, or use [`followup.send`](https://docs.disnake.dev/en/latest/api.html#disnake.Webhook.send "disnake.Webhook.send") directly instead of this method if youโ€™re sending a followup message.
vale wing
#

Returns nothing

hasty raptor
#

Can someone help me with slash commands in my cogs file using the pycord library

maiden fable
#

Hm?

glacial echo
#

MY BOT WORKS LETSS GOOOO

#

i just got my friedn to play it and we had the first successful game

#

this is incredible

maiden fable
#

Yay!

#

Congrats

glacial echo
#

now

#

i either add a random restriction to the words each round and implement a gameover condition, implement a universal game end command, implement the gamemaster role stuff, OR fuck off and code hangman into the bot cause it sounds fairly easy

#

is there a library that will generate a random word

maiden fable
#

Hmmm u will have to use a dictionary module ig

#

!pypi dictionary

unkempt canyonBOT
maiden fable
#

idk if this supports it

glacial echo
#

i found one

#

random-words is a library

#

time to implement the base of a hangman game

#

if i get the UI for it working somewhat ill go to bed

#

hmmmm it says its not installed but it is

slate swan
glacial echo
#

this isnt seeming to work

#

it seems to not be importable in the way the documentation says

vale wing
#

Just use some hangman API pretty sure there are some

maiden fable
#

!pypi hangman

unkempt canyonBOT
maiden fable
#

@glacial echo might as well see its source code ๐Ÿ‘€

slate swan
maiden fable
#

then see it

#

pip show disnake or print(disnake.__version__)

maiden fable
#

Hmm

#

Ah I got the issue

#

See the first line

#

relative imports goes brrrrrr

#

give it a parent package name

glacial echo
#

and wont get me marks

maiden fable
#
>>> from dis import dis
>>> dis(__import__("random"))

Istg don't run this code as long as u don't want to see yr console spammed with lines

glacial echo
#

man

maiden fable
#

๐Ÿ˜” when I changed from random to disnake

glacial echo
#

why is my imports not working

maiden fable
#

๐Ÿคฃ the memory fucked up

slate swan
#

so leave it uh

maiden fable
#

๐Ÿ‘

tired agate
#
@bot.event
async def on_wavelink_track_end(player:wavelink.Player, track: wavelink.Track, reason):
    ctx = player.ctx
    vc : player = ctx.voice_client
    
    if vc.loop:
        return await vc.play(track)
    next_song= vc.queue.get()
    await vc.play(next_song)
    await ctx.send(f"Playing: {next_song.title} rn :)")
@bot.command()
async def play(ctx: commands.Context,*, search: wavelink.YouTubeTrack):
    if not ctx.voice_client:
        vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
    elif not ctx.author.voice:
        return await ctx.send("Pweasee join a VC <3")
    elif not ctx.author.voice != ctx.me.voice:
        return await ctx.send("Pwease be in the same VC <3")
    else:
        vc : wavelink.Player= ctx.voice_client
    if vc.queue.is_empty:
        await vc.play(search)
        await ctx.send(f"Playing: {search.title} rn :)")
    else:
        await vc.queue.put_wait(search)
        await ctx.send(f"Added {search.title} to the queue <3")
    vc.ctx = ctx
    setattr(vc,"loop",False)
@bot.command()
async def queue(ctx: commands.Context):
    if not ctx.voice_client:
        return await ctx.send("Pweasee let me join a VC <3")
    elif not ctx.author.voice:
        return await ctx.send("Pweasee join a VC <3")
    elif not ctx.author.voice != ctx.me.voice:
        return await ctx.send("Pwease be in the same VC <3")
    else:
        vc: wavelink.Player = ctx.voice_client
    if vc.queue.is_empty:
        return await ctx.send("queue is empty :(")

What this should do:
add a song to the queue , and play when the previous song finishes

What bug i get:
Upon adding a song, ignores the queue system and just plays it

I get this error in console:

Ignoring exception in on_wavelink_track_end
wavelink.errors.QueueEmpty: No items in the queue.
maiden fable
#

cannot help with music bots, sorry

vale wing
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeโ€™s robots.txt file; (b) with YouTubeโ€™s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
maiden fable
#

thanks for the honors

vale wing
#

But uh is wavelink related to those

maiden fable
#

Yea

vale wing
#

Ok

maiden fable
#

More or less, both wave and lava link is related to ytdl directly or indirectly

glacial echo
#

wavelinks github mentions spotify not youtube

maiden fable
#

Still against ToS

tawdry perch
#

afaik, spotify doesn't allow it

maiden fable
#

Yup

glacial echo
#

ah

tawdry perch
#

why everyone wants to make music bots ๐Ÿ˜”

glacial echo
#

cause youtube killed all the good ones

#

man why cant i download and use any modules

#

this is so stupid

maiden fable
#

Wym

glacial echo
#

i cant use the random-word module

maiden fable
#

any error?

glacial echo
#

it keeps saying it isnt a module reference

tawdry perch
maiden fable
#

Indeed

maiden fable
glacial echo
#

i have restarted my IDE like 15 times

maiden fable
#

!pypi random_word

unkempt canyonBOT
maiden fable
#

Wrong python version?

vale wing
#

Use a venv and install there

maiden fable
#

U got two?

vale wing
#

Venv good ๐Ÿ‘

maiden fable
#

Hmm I never used that as such lmao

glacial echo
#

that library says it wokrs with 3.10 which im using

maiden fable
vale wing
#

Venv is very convenient

glacial echo
maiden fable
#

wait, can u do py -3.10 -m pip install random_word in the command prompt?

maiden fable
tawny swallow
#

Is there another way to keep my bot online other than using Replit

maiden fable
#

u gotta host it at least anywhere

vale wing
#
py -m venv venv```
CTRL + SHIFT + P -> Select Interpreter -> venv
glacial echo
vale wing
#

Easy

glacial echo
maiden fable
#

Oh my bad

glacial echo
#

you could selfhost or check pins

maiden fable
#

random_word*

vale wing
maiden fable
#

remove the s

glacial echo
#

whats updating pip do

vale wing
#

Pip 22.0 has nice loading bars ๐Ÿ˜€

maiden fable
#

indeed

#

I just love those lmao

glacial echo
vale wing
#

Also before 22.0 there were issues with some modules installation on 3.10

maiden fable
#

idk bout that

#

BTW imagine if u could update Python via pip too ๐Ÿคฃ

vale wing
#

If you tried to install something like scikit you would get weird wheel errors

maiden fable
#

Hmm idk about that

maiden fable
glacial echo
#

imagine if you could update everything via pip

maiden fable
#

related to Python*

glacial echo
#

no, just everything

vale wing
#

I just did sudo do-release-upgrade -d and it updated my ubuntu to 21 with py 3.10

maiden fable
#

Cool

maiden fable
glacial echo
#

anyways

#

still not working

vale wing
#

Then just use venv

#

Venv always works

#

Even without restarting the IDE

maiden fable
vale wing
#

But uh it might require some first usage setup

glacial echo
#

if im doing anyhting more installign and setup stuff im doing it tomorrow tbh

#

its late already

vale wing
#

Like editing regedit

maiden fable
#

stop

glacial echo
maiden fable
#

Hmm and module not found error?

glacial echo
#

ye

maiden fable
#

Can u see yr selected python version from the bottom bar?

glacial echo
maiden fable
#

No

vale wing
#

Oh yeah there might be issues with modules resolving if you have multiple pythons installed

maiden fable
#

From here

glacial echo
maiden fable
#

At the vert bottom

vale wing
#

that's why you should use venv

maiden fable
#

Oh well

glacial echo
#

yea yea i get it venv gud

maiden fable
#

Windows Store goes brrrrrrrrrrrrrr

vale wing
#

Sus

maiden fable
#

most prolly that is the issue

vale wing
maiden fable
maiden fable
vale wing
#

Delete all python versions*

#

And freeze the packages to install them back before

glacial echo
#

kill me

#

i swapped to 3.10.2 normal isntall from the 3.10.3 store version

maiden fable
#

Ah

vale wing
#

Kinda fast

maiden fable
#

then do py -3.10.2 -m pip install disnake

glacial echo
#

i had both

maiden fable
#

in the cli

maiden fable
glacial echo
glacial echo
#

it autoinstalled at some point

maiden fable
#

Hmm, delete it

#

run the Python 3.10.2 installer again and reinstall python launcher

vale wing
#

Check your applications installed, search python and delete all pythons, then just do setup as hunter said and don't forget to check "add python to PATH"

maiden fable
#

Yea

glacial echo
#

ok so windows wont let me uninstall

vale wing
#

๐Ÿ˜ณ

maiden fable
#

And this way, u will remember that Python from Windows Store fucked up my sleep schedule once so I won't install it ever again

maiden fable
#

SmartScreen or smth like that, right?

vale wing
#

SmartScreen usually pops up when you try to actually install

maiden fable
#

Yea, click on More Info and Run Anyway

glacial echo
#

no, a window titled unexpected error

maiden fable
#

Huh show

glacial echo
slate swan
#

nice

glacial echo
#

man why is this so broken

#
client.leadWord[ctx.channel.id] = rw.get_random_word(minLength=5)
    for i in client.leadWord[ctx.channel.id]:
      client.leadWordPoints[ctx.channel.id].append("_")
#

fuck this im going to bed

maiden fable
#

Haha gn!

glacial echo
#

i know iโ€™m too tired to program stuff when i mess up this bad

#

wai i could do client.leadWordPoints[ctx.channel.id] = โ€œ_โ€ * client.leadWord[ctx.channel.id].len()

#

or what we the length function is

slate swan
#
async def on_ready():
    Channel = client.get_channel(908976132550950952)
    Text= "React Below To Get the color role **Red**."
    Moji = await Channel.send(Text)
    await Moji.add_reaction(':redf:')
    await Channel.send(Text)
@client.event
async def on_reaction_add(reaction, ctx, user: discord.Member, role: discord.Role):
  ID = 956441072916107304
  red = discord.utils.get(user.server.roles, name="red")
  if reaction.message.channel.id != ID:
    return
  if reaction.emoji == ":redf:":
    await user.add_roles(role)
    await ctx.send(f"Done :star3:", delete_after=0.4)```

this is my code and the error is:
#

wait ill send ss

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.

Note

This doesnโ€™t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itโ€™s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
slate swan
#

It doesn't take ctx and role.

#

Yes

#

It only takes py async def on_reaction_add(reaction, user): notฬ€```py
async def on_reaction_add(reaction, ctx, user: discord.Member, role: discord.Role):

slate swan
#

k lemme check

#

No?

#

The message is sent with reaction but role is not added .

#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.

Note

This doesnโ€™t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message itโ€™s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
slate swan
#

Read it

#

It takes two arguments, reaction and user.

#

how?

#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
slate swan
#

lol bye gl

#

!d discord.Reaction.emoji

unkempt canyonBOT
slate swan
#

Check if the emoji is what you want, if so add the role to the member.

#
if reaction.emoji == "emoji":
    await user.add_roles(role)
slate swan
slate swan
slate swan
slate swan
#

But it says str too

slate swan
slate swan
#

Removed everything after ctx in9th line

#

k wait

#
async def on_ready():
    Channel = client.get_channel(908976132550950952)
    Text= "React Below To Get the color role **Red**."
    Moji = await Channel.send(Text)
    await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
  ID = 956441072916107304
  red = discord.utils.get(user.server.roles, name="red")
  if reaction.message.channel.id != ID:
    return
  if reaction.emoji == ":redf:":
    await user.add_roles(role)
    await ctx.send(f"Done :star3:", delete_after=0.4)```
#

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

I don't belive :redf: is a valid emoji.

#

So should I add the emoji id thing?

unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

slate swan
#

then what should I do?

#
async def on_ready():
    Channel = client.get_channel(908976132550950952)
    Text= "React Below To Get the color role **Red**."
    Moji = await Channel.send(Text)
    await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user, ctx):
  ID = 956441072916107304
  red = discord.utils.get(user.server.roles, name="red")
  if reaction.message.channel.id != ID:
    return
  if reaction.emoji == ":redf:":
    await user.add_roles(role)
    await ctx.send(f"Done :star3:", delete_after=0.4)```

updated code with error:
#

Instead of user.server do reaction.message.guild.

#

Instead of ctx.send do reaction.message.channel.send

drowsy thunder
slate swan
slate swan
drowsy thunder
slate swan
slate swan
drowsy thunder
glacial echo
#

:redf: ?

slate swan
#

Changed it ._.

slate swan
glacial echo
#

can bots use animated emoji?

vale wing
slate swan
#

Yup they can

slate swan
glacial echo
#

and how do bots using custom emoji work, is it emoji that the owner could use?

vale wing
#

The last return will never be reached

drowsy thunder
#

But the bot should be in the guild where the emoji is from

vale wing
slate swan
glacial echo
#

ah so ideally youโ€™d make a server for your bot to have emojis it might use in its own UI

slate swan
#

Same

glacial echo
drowsy thunder
vale wing
#

Ah you mean that

drowsy thunder
vale wing
#

Bots are basically nitro users but without banners and tag customisation that's it

#

Ofc we can't say they all have nitro

#

Basically they have access to things that are accessible for humans only with nitro

glacial echo
#

why dont bots have custom banners

drowsy thunder
#

@vale wing Exactly,you are correct they dont have the customization and stuff but they can use custom emojis

glacial echo
#

wait bots get anim pfp?

drowsy thunder
#

Dude

slate swan
glacial echo
#

ah

drowsy thunder
#

!rule 7

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

slate swan
slate swan
#
async def on_ready():
    Channel = client.get_channel(908976132550950952)
    Text= "React Below To Get the color role **Red**"
    Moji = await Channel.send(Text)
    await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
  ID = 956441072916107304
  red = discord.utils.get(reaction.message.guild.roles, name="red")
  if reaction.message.channel.id != ID:
    return
  if reaction.emoji == ":redf:":
    await user.add_roles(role)
    await reaction.message.channel.send(f"Done :star3:", delete_after=0.4)```
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
#

` ?

#

Yes

drowsy thunder
#

@slate swan use the format he showed

slate swan
#
@client.event
async def on_ready():
    Channel = client.get_channel(908976132550950952)
    Text= "React Below To Get the color role **Red**"
    Moji = await Channel.send(Text)
    await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
  ID = 956441072916107304
  red = discord.utils.get(reaction.message.guild.roles, name="red")
  if reaction.message.channel.id != ID:
    return
  if reaction.emoji == ":redf:":
    await user.add_roles(role)
    await reaction.message.channel.send(f"Done :star3:", delete_after=0.4)
slate swan
#

With the py

drowsy thunder
#
print(hello*10)
slate swan
#

Oh

drowsy thunder
#

Like that

slate swan
#

py stands for python format.

#
@client.event
async def on_ready():
    Channel = client.get_channel(908976132550950952)
    Text= "React Below To Get the color role **Red**"
    Moji = await Channel.send(Text)
    await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
  ID = 956441072916107304
  red = discord.utils.get(reaction.message.guild.roles, name="red")
  if reaction.message.channel.id != ID:
    return
  if reaction.emoji == ":redf:":
    await user.add_roles(role)
    await reaction.message.channel.send(f"Done :star3:", delete_after=0.4)
drowsy thunder
#

Yes

slate swan
#

I was viewing from my iPad, sorry lol

slate swan
slate swan
#

Yes

#

Nope

#

Well then that code won't work for you.

#

Oh I can't read

#

Sorry

#

Um?

#

Nvm, are you in the right channel when adding the reaction?

#

Yup

#

The message is sent in color roles channel
With reaction
But no role is given

royal wind
slate swan
slate swan
royal wind
#

It never invokes the if statement

slate swan
#

znd?

#

huh

royal wind
#

Yea

#

It keeps making a new object

slate swan
#

huhh

royal wind
#

Even though there's already one

slate swan
#

sten help ๐Ÿ˜” I'm going to play

royal wind
#

I actually wonder, when we pull out collection.find(), I wonder how I should carefully extract the data

#

I thought it would generate something similar to a Python dictionary

slate swan
#

if "user_id" in userData shouldn't it be if author_id in userData?

#

no

royal wind
#

Correct me if I'm wrong, but I want to see if the field user_id exist. author_id is the value of author's ID

#

This is author's id

slate swan
#

iirc, the find method returns a list

#

You are checking if the users id is "user_id".

royal wind
#

I think I know what you meant

#

But then I would probably have to use another aproach

slate swan
#
if author_id in userData:

# not
if "user_id" in userData
royal wind
#

Wouldn't it just verify if we're pulling the correct data?

slate swan
#

Or you might want userData["user_id"]

gaunt ice
#

whats the problem

royal wind
royal wind
slate swan
#

Oh I forgot it was a dict, my bad.

royal wind
#

When someone sends something on to any channel, the bot will obtain the user's ID and then check on to the database to see if this user already has a "profile".

gaunt ice
#

hmm

royal wind
#

If not, it will create one. This is handled by this part of the code

#

You know what, even the first half part of the code seems odd, let me fix that real quick

slate swan
#

I think you want this: ```py
if userData["user_id"]:

royal wind
#

Does that code ask if userData has user_id field?

slate swan
#

It checks if the userData has an user_id in it.

royal wind
#

as a key not a value right?

slate swan
#

It accesses the key, and check if there's a value in it.

slate swan
#

Didnโ€™t typed emoji name because it was gonna be replaced by :redf:

slate swan
#

In that case it returned because you're in the wrong channel.

royal wind
#

I'm stripping everything out. Beginning from here, first, I want to check if there exist a document already for this user. I have the value of author_id which contain user's discord account id.

Assuming I do a lookup based on the account id, and if the user is brand new, there shouldn't be any result coming back. How do I make that logic?

slate swan
#

Oh, you are using != and not ==, so this command will only work if you're in the wrong channel. @slate swan

slate swan
slate swan
slate swan
royal wind
#

What does that None mean?

slate swan
#

It returns None if the user_id isn't in userData.

royal wind
#

okay

#

Let me try

slate swan
vast gale
#

@slate swan uwu

slate swan
royal wind
#

it has no attribute get

slate swan
#

Oh, I thougt userData was a dictionary.

royal wind
#

It's saying it's a cursor

slate swan
royal wind
#

But all the examples on geeksforgeeks is like this

slate swan
#

Even the bots role is above color role

#

Does it print anything?

#

Nope

vast gale
slate swan
# slate swan Nope

Try adding another printstatement at the very beginning of on_reaction_add

#

mhm k

#

When the bot is successfully online it says โ€œhiโ€
And on reaction it says the same

#

I added it after on_reaction_add next line

#

Alright, can you send the current code?

#

k wait

#
@client.event
async def on_ready():
    Channel = client.get_channel(908976132550950952)
    Text= "React Below To Get the color role **Red**"
    Moji = await Channel.send(Text)
    await Moji.add_reaction(':redf:')
@client.event
async def on_reaction_add(reaction, user):
  print("hi")
  ID = 956441072916107304
  red = discord.utils.get(reaction.message.guild.roles, name="red")
  if reaction.message.channel.id == ID:
    return
  if reaction.emoji == ":redf:":
    print('done!')
    await user.add_roles(role)
    await reaction.message.channel.send(f"Done :star3:", delete_after=0.4```
#

Does it work in the on_ready?

#

The one on_ready event I have in the start of code is not working
Which always prints (bot is ready)

#

Do you get any errors?

#

Nope

#

No errors in console

slate swan
#

I can't see the print statement.

slate swan
#

Uh, is it more code in the on_ready event?

#

Ok lemme explain
I have one on ready event at the very start of code for changing bot status and printing that the bot is online
And
The one I sent is this code is different

#

You can't have multiple on_ready events.

#

Only one.

#

Same with all other discord events.

#

Including on_reaction_add.

#

So Iโ€™ll have to remove the bot on_ready?

#

Wonโ€™t that make the bots status = nothing

slate swan
placid skiff
slate swan
#

Is on_ready needed for it?

delicate hornet
placid skiff
placid skiff
slate swan
placid skiff
#

do you added a folder in your cogs folder?

slate swan
placid skiff
#

Mhh can you past the screen or schema of cogs folder?

slate swan
#

I have project about Twitter bot for reply and retweet tweets but i didn't find something to help , do you have any ideas?

placid skiff
#

well that's strange, also i saw that there are two coro which aren't awaited

#

meanwhile you could try something like this for the cogs:

#
COGS = [path.split("\\")[1][:-3] for path in glob("./lib/cogs/*py")]
slate swan
delicate hornet
placid skiff
slate swan
#

uh I see

placid skiff
#

gg

slate swan
#

I'm dumb happy

#

I fixed and got the same error

placid skiff
#

lol

slate swan
slate swan
placid skiff
#

maybe the problem could be that the bot and the setup where you load the cog have a different loop, or you pass that loop to your bot?

placid skiff
#

it really was that? xD

slate swan
placid skiff
#

interesting

slate swan
#

this looks clean though

#

@client.command()
async def add(ctx, args):
    user = ctx.message.author
    role = discord.utils.get(user.guild.roles, name=agrs, permissions=Permissions.all())
    await user.add_roles(role)
    await ctx.send("Role added")```

error 
```py
Ignoring exception in command add:
Traceback (most recent call last):
  File "C:\Users\GUDDU\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\GUDDU\Desktop\Program\Projects with my friends\hack.py", line 30, in add
    await user.add_roles(role)
  File "C:\Users\GUDDU\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 777, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\GUDDU\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\GUDDU\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\GUDDU\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'```
help me out
placid skiff
#

nvm the database import and other things which will not be included

manic wing
#

tell me youre conceited without telling me youre conceited

placid skiff
#

D_D

placid skiff
royal wind
#

Python problem, need help.. It says in my dict, key "user_daily_time" does not exist..

#

But it's there

placid skiff
#

Lol are you sure that you are taking the value at your_dict["key"]?, read better your code

#

it is not saying that your dict doesn't have it, the error is saying that dict object has no attribute user_daily_time

royal wind
#

Sorry, and thank you

#

2 AM brain is hard..

not that 12pm brain would do much anyway

placid skiff
#

np

dense swallow
#
    async def get_logs_channel(self, guild_id):
        data = await self.bot.db.fetchval("SELECT channel_id FROM modlogs WHERE guild_id=$1", guild_id)
        if data:
            return self.bot.get_channel(data)

    async def create_webhook(self, guild_id):
        channel = await self.get_logs_channel(guild_id)
        return await channel.create_webhook(
            name=f"{self.bot.user.name} " + "Logging",
            avatar=self.bot.user.avatar.url,
            reason="For logging"
        )

'NoneType' object has no attribute 'create_webhook'... i cant send the webhook, ik what this error means but when im fetching that channel it works.. but it wont send the webhook

#

im sending the webhook like this:

webhook = await self.create_webhook(ctx.guild.id)
await webhook.send("content here")
placid skiff
#

print the channel var in your create_webhook function

#

let's see if it get the channel

final wagon
#

Can anyone pls help me
i am getting error in heroku in loading cog
Unable to install C enchant library
even though pyenchant is present in my req.txt

royal wind
# placid skiff np

Dude, it works. My goodness I am happy. I can finally sleep. Thank you kind soul

sturdy cloud
#

Guys I want to make a discord bot with Python that will kick members with a command. I made it, but when I am kicking someone I want the bot send a message. How to do that?

unkempt canyonBOT
#

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

placid skiff
#

well if it is a command then you have a context, and the context has a send method, so just use it

dense swallow
#

this is the error it printed

placid skiff
#

i'm not understanding .-.

manic wing
final wagon
#

ohk

cosmic agate
#

how to know which guilds our bot is in?

desert badger
#

do i need 320 kbps audio for a discord music bot ?

cosmic agate
#

no

desert badger
#

since channels are literally just 128 kbps max

cosmic agate
#

no i have music bot and works fine

desert badger
#

so using 128 instead of 320 makes no difference ?

cosmic agate
#

without boost

cosmic agate
desert badger
#

wait can kbps go higher when boosted ?

cosmic agate
#

the latency can

#

go lower

desert badger
#

ill keep it on 64 kbps anyways

cosmic agate
#

and a bit clearer to our ears

cosmic agate
desert badger
#

so 128 completely fine ?

cosmic agate
#

tbh

desert badger
#

thank you ๐Ÿ’œ

cosmic agate
#

how to know which guilds our bot is in?

desert badger
cosmic agate
desert badger
#

uh

cosmic agate
#

ok lets try guild count

desert badger
#
servers = len(client.guilds)
print(servers)
manic wing
#

[guild.name for guild in bot.guilds]

#

or list(map(lambda m: m.name, bot.guilds)) which is quicker

#

why?

#

and?

#

he wants the names

slate swan
#

Doesn't hurt having a list either.

manic wing
#

you have absolutely no logic or reasoning, you're just trying to cause trouble

manic wing
#

you cant print a map object, you can print a list object

#

and...? he wants to see the names not a map object

#

not if you print the map object

slate swan
#

Why are you even arguing about this?

manic wing
#

who knows

#

as i said, he's causing trouble for absolutely no reason at all

slate swan
#

Let TransilP choose the one he wants.

#

Why does my nick command not work?

unkempt canyonBOT
#

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

0 1 2 3 4 5 6 7 8 9
slate swan
slate swan
slate swan
#

Also, no need for setting the embeds title to nothing, it is automatically None.

#

And why do you have pass_context passed into the command?

#

@client.event
async def on_member_join(member):
mbed = discord.Embed(
colour =(discord.Colour.magenta()),
title = 'Welcome Message',
description = 'Welcome{member.mention}, enjoy your stay!')

await member.send(embed=mbed)

#

why its not working

#

someone tell me where am i wrong

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
#

Use that please

#

@slate swan

maiden fable
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
maiden fable
#

Yea thhat too

slate swan
#

closing bracket?

#

which line?

#

Idk, can't see it.

maiden fable
#

wait nvm

#

I misread sorry

slate swan
#

Poeny, can you please use the code format?

slate swan
#

!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
#
@client.event
async def on_member_join(member):
  mbed = discord.Embed(
  colour =(discord.Colour.magenta()),
  title = 'Welcome Message', 
  description = f"Welcome{member.mention}, enjoy your stay!")

  await member.send(embed=mbed)
#

thank u , i now learned it

#

now sm1 tell me whats wrong

#

Great, now fix the intents and make it a f-string.

slate swan
#

Yes, and the intents if you don't already have them.

#

what intents? i gave my bot perms , that one?

#

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

Read it

#
import os
import random
import requests
import json
import discord
from discord.ext import commands
import keep_alive

client = commands.Bot(command_prefix ="%")
#

isnt it enough?

#

No, you need to add the intents.

slate swan
manic wing
#

bot = commands.Bot(command_prefix="!", intents=intents)

slate swan
#
import os
import random
import requests
import json
import discord
from discord.ext import commands
import keep_alive
from discord import Intents


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

bot = commands.Bot(command_prefix="%", intents=intents)
manic wing
#

o.O

slate swan
#

Don't define bot and client twice.

#

Remove the client line.

#

And don't import commands twice either

#

now?

#

Sure

#

Test your command

manic wing
slate swan
slate swan
manic wing
slate swan
manic wing
#

doesnt matter

#

he can just do keep_alive.keep_alive

slate swan
#
from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def main():
  return "Hello, I am running!"

def run():
  app.run(host="0.0.0.0", port = 8080)

def keep_alive():
  server= Thread(target=run)
  server.start()
manic wing
#

we know

slate swan
slate swan
#

Any error?

#

replit PeepoShy

slate swan
slate swan
#
  • Running on http://172.18.0.118:8080/ (Press CTRL+C to quit)
    172.18.0.1 - - [24/Mar/2022 10:35:30] "GET / HTTP/1.1" 200 -
    WE HAVE LONGED IN
#

Nicely spelled.

junior verge
#
import discord
from discord.ext import commands
import json

class Setlog(commands.Cog):

    def __init__(self, client):
        self.client = client

        with open('log_channels.json', 'r') as f:
        log_channels = json.load(f)

        @client.command()
        @commands.has_permissions(administrator = True)
        async def modlog(self, ctx, channel = None):

        log_channels[str(ctx.guild.id)] = channel.split()
        with open('log_channels.json', 'w') as f:
            json.dump(log_channels, f)
        await ctx.send(f'Mod log set to {channel}')

def setup(client):
    client.add_cog(Setlog(client))
``` I am not sure how to do this but how do I make a command to set a log channel
slate swan
junior verge
#

oh lmao

#

I am in cogs

#

but still

slate swan
#

And the command shouldn't be inside __init__.

slate swan
junior verge
#

oh lol

#

but the log_channels[str line has intent problems it says

slate swan
#

Yeah, indent it once.

junior verge
junior verge
maiden fable
slate swan
#

๐Ÿ˜“

junior verge
#

I did

#
import discord
from discord.ext import commands
import json

with open('log_channels.json', 'r') as f:
        log_channels = json.load(f)

class Setlog(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command()
    @commands.has_permissions(administrator = True)
    async def setlog(self, ctx, channel = None):

    log_channels[str(ctx.guild.id)] = channel.split()
    with open('log_channels.json', 'w') as f:
        json.dump(log_channels, f)
    await ctx.send(f'Mod log set to {channel}')

def setup(client):
    client.add_cog(Setlog(client))
maiden fable
#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

junior verge
#

aahh

#

lemme try

maiden fable
#

Haha

junior verge
#

was just a dumb mistake

maiden fable
#

All cool

#

as long as u understand yr mistake

junior verge
#

let me try if this works

#

yeah

#

I can't push

maiden fable
#

Ah

#

first do git pull

junior verge
#

still same error

maiden fable
#

show

manic wing
#

whats the git pull output

junior verge
#

No error when pulling

maiden fable
#

pull

junior verge
#

did

manic wing
#

show the pul outpu

maiden fable
#

then push

junior verge
maiden fable
# junior verge

ah, u edited yr code locally before pushing which has resulted in errors

junior verge
#

I never had this before lol

manic wing
#

basically the code in the remote is different to your local

#

so you have a couple options

#

either you stash all the code, pull and then pop it

#

which is probably the best way

#

or you reclone it and move your files

#

or you can just stash it and not pop it

junior verge
#

so how to fix it

maiden fable
#

Lmao

manic wing
#
git stash
git pull
git stash pop
git push```
junior verge
manic wing
#

whats git status output

junior verge
manic wing
#

it tells you what to do; do git add .

junior verge
manic wing
#

yes

junior verge
#

I usually do git add *

manic wing
junior verge
manic wing
#

did you do git stash?

junior verge
#

ye

manic wing
#

what was the output to git stash

junior verge
manic wing
junior verge
#

thats it

manic wing
junior verge
#

so

#

what now

slate swan
junior verge
#

wdym

slate swan
#

git push -f

#

that works for me everytime i get that error

junior verge
slate swan
#

yeah

#

its pushed

#

to the master branch

#

of your repo

junior verge
#

yep ty

slate swan
slate swan
maiden fable
slate swan
manic wing
maiden fable
#

mhm

slate swan
#

dont know what you mean by that peepoAExit

maiden fable
#

I ain't explaining anything I hate git anyways

manic wing
#

why

#

its really easy when you get the hang of it

slate swan
maiden fable
minor totem
#

Just don't push commits until you're 100% happy with them

maiden fable
#

Rest all, VSCode handles for me

maiden fable
slate swan
maiden fable
#

I know

slate swan
#

welp, your choice

maiden fable
#

I never really had to use any other commands, so never really saw the docs as much

maiden fable
#

Yea oki, use the ot command now ๐Ÿ‘

slate swan
#

nice

slate swan
unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

slate swan
#

also

#

which users does the bot track in the on_user_update event

maiden fable
#

bot.users

slate swan
#

ew

#

alright

#

thanks PepeOK

maiden fable
#

Wasn't that obvious tho

slate swan
#

so i asked a question that was completely irrelevant to me GWcmeisterPeepoShrug

maiden fable
#

Lmao

junior verge
#

When I do .setlog #channel my github doesn't update. How do I gotta do that when I use github heroku

boreal ravine
#

why would the repository update

junior verge
#

Yeah I know

#

But how do I do that then uhm

hushed field
#

a database?

junior verge
#

yeah but idk how

iron sorrel
#

sqlite or json database

#

json db is easier tbh
but sql is better

junior verge
#

json

vale wing
iron sorrel
#

whats your limitations?

junior verge
#

I use heroku with github

vale wing
iron sorrel
vale wing
#

Those don't even stay near

iron sorrel
#

and json database is easy to make for beginners,

no one starts with sql

vale wing
junior verge
#

Well I don't know how to do that with a discord bot, set a log channel

vale wing
#

Don't even use such term "json database", there are "json-like databases" but a bunch of json files or a single json file can't be considered a database

vale wing
#

That's implementable with webhooks, you don't even need a bot

junior verge
#

Set a log channel with a database

vale wing
#

Oh

#

You could make an architecture in which all the queries would go to one function and that function would always log what it is supposed to

junior verge
#

Yeah I got no clue to do that

vale wing
#
async def exec_query(query, ...):
    await db.execute(...)
    log.info("Query executed: %s", query)```
pliant gulch
# junior verge I use heroku with github

If your storing data to a file in Heroku, it will refresh the state of the file back to how it was on the push, this is because heroku uses an ephemeral file system

#

In order to store data on heroku that changes, youโ€™d need a database hosted outside of heroku

junior verge
#

yeah but idk how sad

vale wing
#

Maybe it provides separate databases

maiden fable
vale wing
#

But basically just use a VPS

#

Digital ocean free 100$ for two months, amazon AWS free server for a year

slate swan
#

const express = require("express");
const app = express()

app.listen(3000,() => {
console.log("project is running!")
})

app.get("/", (req, res) => {
res.send("Hello world!");
})

const Discord = require("discord.js");
const Client = new Discord.Client({intents : ["GUILDS", "GUILD_MESSAGES"]});

client.on("message", message => {
if(message.content === "ping") {
message.channel.send("pong");
}
})

client.login(process.env.token);

vale wing
#

Vultr has free options as well but they aren't really "free" as they charge you to activate bonus

maiden fable
slate swan
#

so i have this in my on_message and it basically reply every time it got mention and i wanna ask if there's anyway i can except the @everyone @here cuz it automatically reply whenever we mention the @everyone @here

slate swan
#

Then add and check if @everyone and @here isn't in there.

#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

boreal ravine
slate swan
#

thanks

#
if member.mention in message.mentions:
brisk zodiac
#

Why is it error?

import os
import discord
from discord.ext import commands
from discord.utils import get
from keep_alive import keep_alive
from discord import Intents

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

client = discord.Client()

client = commands.Bot(command_prefix="!", intents=intents)

client.remove_command("help")

@client.event
async def on_member_join(member):
    channel = discord.utils.get(member.guild.channels, name="general")
    await channel.send(f"{member.mention} has just joined the server!")

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

keep_alive()
client.run(os.getenv('TOKEN'))```
manic wing
#

o.O

#

remove client = discord.Client

brisk zodiac
#

Oh okay

brisk zodiac
manic wing
#

what's the error though

brisk zodiac
#

File "main.py", line 27, in <module>
client.run(os.getenv('TOKEN'))
File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run

  • Running on all addresses.
    WARNING: This is a development server. Do not use it in a produc
  • Serving Flask app '' (lazy loading)
  • Environment: production
    WARNING: This is a development server. Do not use it in a production deployment.
    Use a production WSGI server instead.
  • Debug mode: off
  • Running on all addresses.
    WARNING: This is a development server. Do not use it in a production deployment.
  • Running on http://172.18.0.97:8080/ (Press CTRL+C to quit)
    Traceback (most recent call last):
    File "main.py", line 25, in <module>
    client.run(os.getenv('TOKEN'))
    File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 723, in run
    return future.result()
    File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 702, in runner
    await self.start(*args, **kwargs)
    File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 665, in start
    await self.login(*args, bot=bot)
    File "/home/runner/Welcoming-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 511, in login
    await self.http.static_login(token.strip(), bot=bot)
    AttributeError: 'NoneType' object has no attribute 'strip'
manic wing
#

you need to load the .env

#

!pypi python-dotenv

unkempt canyonBOT
brisk zodiac
#

ah ok

manic wing
#

from dotenv import load_dotenv; load_dotenv()

brisk zodiac
#
import os
import discord
from discord.ext import commands
from discord.utils import get
from keep_alive import keep_alive
from discord import Intents
from dotenv import load_dotenv

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

client = commands.Bot(command_prefix="!", intents=intents)

client.remove_command("help")

@client.event
async def on_member_join(member):
    channel = discord.utils.get(member.guild.channels, name="general")
    await channel.send(f"{member.mention} has just joined the server!")

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

keep_alive()
client.run(os.getenv('TOKEN'))``` Is this right?
manic wing
#

sure

brisk zodiac
#

But still error

slate swan
#

Do this:```py
client.run(os.getenv["TOKEN"])

brisk zodiac
#

Okay

slate swan
#

It should be with [] not ().

brisk zodiac
#

Traceback (most recent call last):
File "main.py", line 27, in <module>
client.run(os.getenv["TOKEN"])
TypeError: 'function' object is not subscriptable

#

Error

final iron
manic wing
slate swan
#

Oh

#

Yeah sorry

manic wing
slate swan
#

@slate swan thank u it works

#

What works?

#

do anyone tell me how to send welcome msg in the chanel

brisk zodiac
slate swan
slate swan
slate swan
#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
final iron
slate swan
#

Get the channel and then use .send() on it.

#

the promblem is getting the channel