#discord-bots

1 messages · Page 1097 of 1

rocky hornet
#

didnt i send you the code

cloud dawn
# rocky hornet didnt i send you the code

You sended the ss but you are already working in the Message object so you can just use MessageReference so I have no clue as of why you are making this and where there is an issue.

rocky hornet
#

if Message object (self) has a reference, I want to get the Message that represents that reference

#

essentially the Message that was replied to

#

or None if there's no reply

#

are you with me?

rocky hornet
cloud dawn
#

So aka the replied message.

rocky hornet
#

yeah

#

and nobody seems to know the best way of doing this

cloud dawn
#

Oh i get it lmfao

rocky hornet
cloud dawn
#

Does this work? Or do you want a better/ shorter version?

#

It looks pretty solid besides from the fact that the typehint is wrong and it could return a DeletedReferencedMessage as well.

rocky hornet
rocky hornet
cloud dawn
#

Oh yeah.

rocky hornet
#

alright then

#

thanks for trying your best to explain this thing xd

cloud dawn
#

I fully understand it now of you want me to explain it fully.

rocky hornet
#

yes please

cloud dawn
#

I assume the async get ... is clear?

rocky hornet
#

async get?

#

you mean fetch_message?

cloud dawn
#

This line any questions?

rocky hornet
#

I made this function

#

so I know how it works

#

then i do this
disnake.Message.getch_reference_message = get_or_fetch_reference_message

#

monkey patching kek

cloud dawn
rocky hornet
rocky hornet
heady sluice
#

o

#

clear

rocky hornet
#

i can show u the whole file

cloud dawn
rocky hornet
cloud dawn
rocky hornet
#

that means something else sets it on the message

rocky hornet
oblique adder
#

async def on_raw_reaction_remove(self,payload : RawReactionActionEvent):

How do I check if a member is already react to one of the emoji in this message and if yes remove it . ?

rocky hornet
nocturne ridge
#

Guys how can I make my bot post a random image from a subreddit with PRAW?

rocky hornet
#

resolved = None

cloud dawn
nocturne ridge
#
    if message.content == ('$meme'):
        sub = random.choice(meme_subreddits)
        print(f"GETTING A MEME FROM r/{sub}")
        submission = reddit.subreddit(sub).random()
        await message.channel.send(submission)
``` this give the link to the submission
oblique adder
paper sluice
nocturne ridge
#

what is asyncpraw?

rocky hornet
#

because i only need message object

paper sluice
paper sluice
slate swan
#

.

rocky hornet
#

I see

#

thanks that was helpful!

paper sluice
#

i hate it when in a class they define the init in the bottom

cloud dawn
#

I just ctrl-f it anyways.

cloud dawn
rocky hornet
#

works in 3.10

cloud dawn
#

rip slots

slate swan
#
import task

@task.loop(second=5)
async def Recover(ctx):
    for channel in ctx.guild.channels:
        if channel.name in ('rules', 'moderator-only'):
            try:
                await channel.delete()
            except:
               pass 
``` @paper sluice this is correct?
paper sluice
#

why are you deleting every 5 seconds?

slate swan
paper sluice
#

@slate swan its better you ask your question here itself, dont DM.

heady sluice
#

logically, no, no channel is named just rules

#

or moderator-only

#

also missed an s on tasks

#

and tasks don't have ctx

slate swan
heady sluice
#

no

slate swan
#

Nothing

heady sluice
#

all in all, that code is also programmingly wrong

slate swan
spring flax
#

i have ```py

async def connect_subreddit():
global subreddit
subreddit = await reddit.subreddit("ApexLegendsMobile")

@bot.listen()
async def on_ready():
await connect_subreddit()
print("bot is ready")

@bot.listen()
async def on_ready():
await connect_subreddit()
print("bot is ready")

@tasks.loop(seconds=1)
async def get_reports():
async for item in subreddit.mod.stream.reports():
print(item)

and it raises ```
    async for item in subreddit.mod.stream.reports():
NameError: name 'subreddit' is not defined
heady sluice
#

two on_readys

#

don't you have to global subreddit

spring flax
#

whoops

spring flax
heady sluice
#

not in get_reports

spring flax
#
async def connect_subreddit():
    global subreddit
    subreddit = await reddit.subreddit("ApexLegendsMobile")
#

i have this

heady sluice
spring flax
#

i don't understand

heady sluice
#

global subreddit in your task, but maybe I'm wrong

cloud dawn
spring flax
#

well i know how to make basic bots what exactly is wrong with that i am doing? at least the line

heady sluice
#

!botvar > global vars

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

spring flax
#

okay but

flint isle
#

Can bots only be in one voice channel?

heady sluice
#

yes

#

except shards

flint isle
#

So I would have to shard the bot to overcome that?

heady sluice
#

yes

lyric apex
#

How to handle this error?

heady sluice
#

commands.MissingPermissions?

lyric apex
#

!d discord.ext.commands.BotMissingPermissions

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/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
#

Hey @slate swan! 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!

slate swan
#
import discord

bot = discord.Client()
intents = discord.Intents.default()
intents.members = True
token = ""




async def on_ready():
  print ("Ready")

@bot.event
async def on_voice_state_update(member, before, after):
    targetID = ("921082510471987261")

    if before.channel is None and after.channel is not None and member.id == targetID.id:
        await member.voice.channel.connect()

bot.run(token)```
#

i get a error with that code

lyric apex
#

Show

slate swan
#

okay one second

lyric apex
#

targetID is NoneType

slate swan
lyric apex
slate swan
#

Alright tryign rn

#

the code is suppose to work when someone joisn the call the bot auto joins

#

and the code above doesn't work out

potent spear
neat field
#
    def __init__(self, ctx : discord.Interaction, opt1, opt2, opt3):
        super().__init__(timeout=60)
        self.value = None``` ```    @discord.ui.button(label=opt1, style=discord.ButtonStyle.blurple)
    async def option1(self, interaction: discord.Interaction, button: discord.ui.Button):
        self.value = self.option
        for button in self.children:
            button.disabled=True
        await interaction.response.edit_message(view = self)
        self.stop()``` How can i make the arg `opt1` be the label?
fading marlin
#

after your super call, set self.option1.label to opt1

wicked atlas
#
self.option1.label = opt1
halcyon basalt
#
import os
import discord
import random
from discord.ext import commands
from discord_slash import SlashCommand
from discord_slash.utils.manage_commands import create_option, create_choice, create_permission
from discord_slash.model import SlashCommandPermissionType

bot = commands.Bot(command_prefix="!", description = "Bot tuto")
slash = SlashCommand(bot, sync_commands = True)

@bot.event
async def on_ready():
    print("Ready !")

@slash.slash(name="size_femme", guild_ids=[916447427605725194], description="voir les tailes femme us en eu ")
async def size_femme(ctx):
    await ctx.send("https://www.sports-loisirs.fr/img/cms/guides%20pointure/Pointures-femme-Nike.jpeg")


@slash.slash(name="size_homme", guild_ids=[916447427605725194], description="voir les tailes homme us en eu ")
async def size_homme(ctx):
    await ctx.send("https://www.sports-loisirs.fr/img/cms/guides%20pointure/Pointures-homme-nike.jpeg")

@slash.slash(name="raffle", guild_ids=[916447427605725194], description="voir les sites qui prélèvent ou non lors de raffle")
async def raffle (ctx):
    embed =  discord.Embed (title = ("Guides des prélevements pour les raffles"),description = ("-"))
    embed.add_field(name = ("__sites qui prélèvent__"),value=("-afew\n" "-consortuim\n""-Cornerstreet\n""-Footpatrol\n" "-GrosBaskets\n" "-Hanon\n" "-kickz\n" "-JD sport\n" "-Seventstore\n" "-size\n"))  
    embed.add_field(name = ("__sites qui ne prélèvent pas__"),value=("-Basket4Ballers\n" "-BSTN\n""-Courir\n""-END\n" "-Fenom\n" "-Footshop\n" "-Goodhood\n" "-Kith\n" "-Noirfonce\n" "-One Block Down\n" "-shinzo\n" "-Slam Jam\n" "-Sivasdescalzo\n" "-SNS\n" "-4 elementos\n" ))
    await ctx.send(embed = embed) ```
heady sluice
#

or set self.opt1 = opt1 in your __init__

#

then just use self.opt1

halcyon basalt
#

thx for your help

heady sluice
#

huh

fading marlin
heady sluice
#

that's a good point

#

but you still have to set self.opt1 in the init

#

oh nah you don't

wicked atlas
halcyon basalt
heady sluice
halcyon basalt
#

ok its good bu i have this now xd

#

what is missing acces

neat field
#

@fading marlin @wicked atlas Tysm rly apreciate it

heady sluice
#

no access to a server with such id I suppose

wicked atlas
#

The bot dosen't have permissions to update slash commands on the server you want to update them on

heady sluice
#

or you have access to the server but no access to the commands there

#

it's 6am but Imma go sleep

wicked atlas
#

Or no, it looks like it dosen't have permissions to see them

heady sluice
#

give your bot app commands scope

wicked atlas
#

When you invited your bot, did you remember to check off the applications.commands permission?

heady sluice
#

what did you do in code

halcyon basalt
#

a tools for sneakers

#

to have a size chart and other things

halcyon basalt
heady sluice
#

you have lots of unnecessary imports

regal pulsar
#

just do bot.slash_command()

regal pulsar
slate swan
#

just use aiohttp 😔

nocturne ridge
#
    if message.content.startswith("$reddit "):
        e = message.content[8::]
        submission = reddit.subreddit(e).random()
        await message.channel.send(f"**Tytuł: **{submission.title}\n**Sub: **r/{e}\n**Autor: **{submission.author}\n{submission.url}")
        for top_level_comment in submission.comments:
            await message.channel.send(top_level_comment.body)
```how can I make it not send over 50 messages in some cases? I want to cap it to max 10 comments
cloud dawn
#

Just add [:10] after submission.comments

regal pulsar
#

wrong password?

#

auth error

spring flax
# regal pulsar wrong password?

Yeah, so the password I am putting is the password for the email that the account is logged in under, and the username is the account's random username which it set me. So I'm not sure what's wrong

#

at least, i'm pretty sure it's the right one

slate swan
#

Is there a limit to change discord bots pfp using the code?
Like I want to try my bot to match pfp with someone but I'm afraid the rate limit will ruin it.

regal pulsar
spring flax
#

i have all those

slate swan
maiden fable
cloud dawn
#

more like 0.5

maiden fable
#

That is the global one

#

Ratelimits are dynamics

shrewd apex
#

roughly smh

maiden fable
maiden fable
shrewd apex
#

anyone recommend any good MySQL tutorials especially one with good joins and group bys

maiden fable
#

Sarth prolly knows

cloud dawn
slate swan
#

AttributeError: 'NoneType' object has no attribute 'send' help me please

@tasks.loop(seconds=30)
async def search_deal():
    channel = bot.get_channel(928755667286769679)
    deals = dealabs.get_hot_deals(params={})
    for deal in deals["data"]:
        embed = discord.Embed(title=deal["title"], description="Description", color=0x00ff00)
        embed.add_field(name="Price", value=deal["price"], inline=False)
        embed.add_field(name="HOT", value=deal["temperature_rating"], inline=False)
        await channel.send(embed=embed)
        print("Nouveau Deal")




search_deal.start()```
maiden fable
#

channel id wrong

slate swan
#

yet the id is correct

vocal plover
#

possibly more likely the task is being started before the bot has received all the necessary data to resolve that channel in a READY event

#

you might be able to add await bot.wait_until_ready() at the start of the function to fix it

#

which will ensure nothing runs until you have populated the cache with that data

slate swan
vocal plover
#

You can receive the ready event multiple times in the program's lifecycle, so I wouldn't recommend starting it there in case the start method gets called a few times

slate swan
#

anyone know how to get the price of a dealabs to embed it ?

#

@maiden fable @shrewd apex thx!!

maiden fable
#

(:

slate swan
#

@maiden fable nice pfp haha.

maiden fable
#

Thanks

shrewd apex
maiden fable
odd mango
#

one of my TOGGLE commands changes bot status to nothing
when the command is toggled again, i want it to change to what is mentioned in
bot = commands.Bot(command_prefix='a!', activity=discord.Game(name="abc"), intents=intents, help_command=MyHelp())

is there any way other than doing
await client.change_presence(activity=discord.Game(name="abc"))?

#

cause changing the activity often is not good right?

maiden fable
#

u can change the activity for upto 30 times a minute (max requests in a min for the ws are 120 per minute)

odd mango
#

still

sick birch
#

I'm not understanding the question here

odd mango
#

is there any way using which i can do something like
await client.change_presence(whatever is default)

maiden fable
#

I just understood the "cause changing the activity often is not good right?" so I just told him about the ratelimit stuff

odd mango
#

oml

sick birch
odd mango
#

bot = commands.Bot(command_prefix='a!', activity=discord.Game(name="abc"), intents=intents, help_command=MyHelp())

sick birch
#

Ah, you can save that to a variable:

default_status = discord.Game(name="abc")
bot = commands.Bot(command_prefix='a!', activity=discord.default_status, intents=intents, help_command=MyHelp())

# whenever you need to reset presence to "default":
await bot.change_presence(activity=default_status)
odd mango
#

got it

#

thanks a lot

odd mango
slate swan
#

Dear, tell me what is wrong? the bot should delete messages containing 1 and 2 and it deletes everything

    @commands.Cog.listener()
    async def on_message(self, message):   
        bad_words = ["1", "2"] 
        await self.client.process_commands(message)

        msg = message.content.lower()
        msg1 = msg.split () # Делит сообщение пользователя на список из слов.
        for bad_words in msg1: # Проверяет есть ли в сообщении пользователя это слово.
            await message.delete()
            await message.author.send( "айайай")
sick birch
#

Maybe it's picking up your own messages?

slate swan
#

Don't know. here it is written in the code that if msg contains a word from the list, then it is deleted. he deletes everything

pliant gulch
#

for bad_words in msg1 doesn't iterate the tokenised string for each bad word, it iterates the string then places the value into bad_words

#

You are thinking about it too literally

#

You should just iterate the string, then check if that word is in bad_words

unkempt canyonBOT
#

Hey @wild spoke!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

wild spoke
#

I tried using FORWARDGRAM discord script but for some reason it does not work

slate swan
#

looking to make if someone joins a VC the bot joins as well ^

wild spoke
slate swan
#

import os
import discord

bot = discord.Client()
intents = discord.Intents.default()
intents.members = True
token = ""

async def on_ready():
print ("Ready")

@bot.event
async def on_voice_state_update(member, before, after):
targetID = ("921082510471987261")

if before.channel is None and after.channel is not None and member.id == targetID.id:
    await member.voice.channel.connect()

bot.run(token)
looking to make if someone joins a VC the bot joins as well ^

devout iris
#

Hia

#

How to clone a channel?

wild spoke
#

why it gives me this traceback?

_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<function on_ready at 0x00000223F8B181F0> exception=SystemExit(None)>
Traceback (most recent call last):
  File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 698, in run
    loop.run_forever()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 601, in run_forever
    self._run_once()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1905, in _run_once
    handle._run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Kastle\tg2ds\discord_messager.py", line 46, in on_ready
    quit()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\_sitebuiltins.py", line 26, in __call__
    raise SystemExit(code)
SystemExit: None
odd mango
#

how do i hide a command from subclassed help command?

nocturne ridge
#

how can I get the mount of servers joined and make it a string??

sick birch
#

I assume you know how to convert to a string using str() as that's pretty elementary

nocturne ridge
#

ye

#

bro how could I make a bot but not know how to convert something to string

#

i mean there can be some people

sick birch
#

Huh?

nocturne ridge
#

:) forget it

sick birch
#

I'm not fully following what you're saying

nocturne ridge
#

me too

wild spoke
#

Guys have anybody used telegram to discord forwarder?

nocturne ridge
#

i may have it on a different name

#

or none at all

odd mango
#

client?

#

none at all is not possible

nocturne ridge
#
client = discord.Client()
```this?
odd mango
#

yeah

nocturne ridge
#

k thanks

odd mango
#

replace bot with client and try

nocturne ridge
#

or I can do len(client.guilds)

#

same thing

odd mango
#

thats what i said ://

nocturne ridge
#

oh

#

right lol sorry

#

i missunderstood

odd mango
#

thats alright

spring flax
#

How do I fetch a channel? basically so that it never returns None

#

i currently am doing bot.get_guild and guild.get_channel but it returns None

maiden fable
#

!d discord.Guild.fetch_channel (:

unkempt canyonBOT
#

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

Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel") or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.

Note

This method is an API call. For general usage, consider [`get_channel_or_thread()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_channel_or_thread "discord.Guild.get_channel_or_thread") instead.

New in version 2.0.
spring flax
maiden fable
#

Also there are only edge cases (if u don't take no-intent situations) when a channel returns None

spring flax
#

nevermind, thanks

pliant gulch
#

I'd do Bot.fetch_channel

#

So you won't need to find the guild

maiden fable
#

Bot.fetch_channel is robust, yea

pliant gulch
#

Channel IDs are unique, so there is really no need for the guild

#

Unless you use it later, even then it's given with Channel.guild

spring flax
#

so code does nothing no errors

#
@tasks.loop(seconds=10)
async def get_reports():
    subreddit = await reddit.subreddit("subreddit")
    async for report in subreddit.mod.reports():
        channel = bot.fetch_channel(985240317743738981)
        e = disnake.Embed(
            description=f'A post was reported [here](https://reddit.com{report.permalink}',
            color=disnake.Color.blurple()
        )
        await channel.send(embed=e)

        
        
get_reports.start()
pliant gulch
#

Also make sure get_reports has an wait_until_ready call

#

Otherwise the cache will not be populated, that'll probably be the cause for the None issue before

spring flax
#

ooh okay yeah thanks

cloud dawn
#

I also don't recommend re-fetching the channel for every post.

pliant gulch
heady sluice
#

oh it was get before

deft anvil
#

hello id like to make my bot send a message in a chhannel when someone reaches a total amount of messages in my server, is that possible?

heady sluice
#

it's hard

#

and probably gonna get you ratelimited

wild spoke
#
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<function on_ready at 0x00000142A6AC81F0> exception=SystemExit(None)>
Traceback (most recent call last):
  File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 698, in run
    loop.run_forever()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 601, in run_forever
    self._run_once()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1905, in _run_once
    handle._run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Kastle\tg2ds\discord_messager.py", line 46, in on_ready
    quit()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\_sitebuiltins.py", line 26, in __call__
    raise SystemExit(code)
SystemExit: None

What can possibly trigger this traceback?

heady sluice
#

dunno but you did it on_ready

#

and das not good

#

oh you did quit()

#

well why would you do that

wild spoke
#

No, I found repo on Git

heady sluice
#

so you copied it

wild spoke
#

I did all right like shown in instructions, but discord script does not work

#

Telegram one does

heady sluice
#

don't quit()

wild spoke
#

how

#

(im noob in python)

heady sluice
#

just don't

wild spoke
#

import yaml
import sys
import logging
import discord

''' 
------------------------------------------------------------------------
    DISCORD CLIENT - Init the client
------------------------------------------------------------------------
'''

discord_client = discord.Client()
with open('config.yml', 'rb') as f:
    config = yaml.safe_load(f)

''' 
------------------------------------------------------------------------
    MESSAGE AS WE RECIEVE FROM FORWARDGRAM SCRIPT
------------------------------------------------------------------------
'''

message = sys.argv[1]

''' 
------------------------------------------------------------------------
    DISCORD SERVER START EVENT - We will kill this immaturely
------------------------------------------------------------------------
'''
# when discord is initalized, it will trigger this event. 
# we quickly send messages to our discord channels and quit the script prematurely.
# this gets trigged again when a new message is sent on channel from telegram

@discord_client.event
async def on_ready():

    print('Есть контакт с пользователем {0.user}'.format(discord_client))
    print('Ждем сообщения')

    # My channels are for RTX card drops and PS5
    channel_1 = discord_client.get_channel(config["discord_1_channel"])


    if 'Mario' in message:
        await channel_1.send(message)

    quit()

discord_client.run(config["discord_bot_token"])

#

Thats the script

heady sluice
#

there

#

wait wth

#

what is this

wild spoke
#

it fetches message, taken from telegram forwader and makes bot to send it to discord channel

warped mirage
#

Anyone know how to make smth like this ? A on_member_join event

placid verge
warped mirage
heady sluice
#

ofc

placid verge
warped mirage
#

Alr

wild spoke
placid verge
#

but I'll probably go to bed soon so

heady sluice
#

that script doesn't even have on_ready

#

or I'm blind

wild spoke
#

i dont know what the hell is this

#

I just want to forward telegram messages to discord

heady sluice
#

I suggest

#

python

wild spoke
#

?

heady sluice
#

also learning python

wild spoke
#

Whats what I am doing

#

watching how the script works

#

but it does not

#

and I can't contact the dev

heady sluice
#

that script is really complicated

wild spoke
heady sluice
#

like really really complicated

wild spoke
heady sluice
#

I suggest learning python basics, then object oriented programming, and one API (wrapper) at a time

wild spoke
#

and I suck at that

heady sluice
#

that's a problem

wild spoke
#

I literally don't understand

heady sluice
#

it's not THAT hard

#

you define a table, you define what a table can do, you make a table and use it

wild spoke
#

english termins

heady sluice
#

I started programming with java

#

which is basically c#

#

both of those languages use oop

#

great practice

wild spoke
#

We are forced to use C++

#

and python is only one class per week

heady sluice
#

idk man I don't have all that in school

wild spoke
#

The only thing I understood is that problem is somewhere here

async def on_ready():

    print('Есть контакт с пользователем {0.user}'.format(discord_client))
    print('Ждем сообщения')

    # My channels are for RTX card drops and PS5
    channel_1 = discord_client.get_channel(config["discord_1_channel"])


    if 'Mario' in message:
        await channel_1.send(message)

    quit()

discord_client.run(config["discord_bot_token"])
heady sluice
#

yeah all the things that are under

My channels are...

are supposed to be in an on_message event

wild spoke
#

amount of channels is as the same as in config file

heady sluice
#

and you should remove quit()

#

that's like a main issue

wild spoke
#
 Discord Channels | No quotes
discord_1_channel: (deleted)

#

I have this in config

heady sluice
#

discors_1_channel is supposed to be a channel id

wild spoke
#

yes

heady sluice
#

so just a huge number

wild spoke
#

I removed it for safety measures

heady sluice
#

oh

wild spoke
#

i have it in config

heady sluice
#

it doesn't matter we can't do anything with the id

#

so I suppose the message would be defined by the on_message

#

but what did you mean to send there

wild spoke
#
if 'Mario' in message:
        await channel_1.send(message)
#

this?

heady sluice
#
@bot.listen()
async def on_message(message):
    # My channels are for RTX card drops and PS5
    channel_1 = discord_client.get_channel(config["discord_1_channel"])


    if 'Mario' in message.content:
        await channel_1.send(message)
#

quick sum up

#

yeah that

pliant gulch
#

I don’t think discord.Message has contains

#

Do you mean message.content?

heady sluice
#

oh it doesn't

wild spoke
#
message = sys.argv[1]
heady sluice
#

...

#

where sys.argv[1] is?

wild spoke
#
 # This is probably not the best way to do this but definitely the easiest way. 
            # When message triggers you start discord messanger script in new thread and sends parsed input as sys.argv[1]
#
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} {{CONFIG_PATH}}")
        sys.exit(1)
    with open(sys.argv[1], 'rb') as f:
        config = yaml.safe_load(f)
    start(config)
heady sluice
#

this guy used google translator for comments I swear

wild spoke
#

mby

pliant gulch
#

C semantics 😳

heady sluice
#

andy can you take over

#

😭

heady sluice
wild spoke
heady sluice
#

but you definitely don't wanna send it in a discord message

sick birch
#

you know if all you're doing is forwarding the easiest way might be to just use the raw send message endpoint

#

No need for a full fledged websocket connection

heady sluice
#

do we wanna act like we understood that

pliant gulch
#

By that I mean the one triggering the forwarding

sick birch
#

Telegram probably has a websocket API similar to discord maybe?

wild spoke
sick birch
heady sluice
#

you use overkill shit

#

for easy stuff

pliant gulch
#

Is this just telegram -> discord or is it bi-directional?

sick birch
#

This is pretty easy, all you need is aiohttp (could even get away with requests)

pliant gulch
wild spoke
heady sluice
#

but with requests, WE won't be happy

sick birch
#

Then yeah should be very easy

pliant gulch
#

Ok then yea rest only would be needed

wild spoke
#

Tg channels to be exact

sick birch
#

Hard part is figuring out how to hook into Telegram's API

wild spoke
#

Hard part is figuring how to think outside hello world

pliant gulch
#

Use whatever flavour telegram wrapper, one that can subscribe to a message event (or whatever is equivalent, cause idk) then just send a POST request to discord.com/api/v9/channels/id/messages with proper auth headers and the message payload

wild spoke
#

what

sick birch
#

Using requests/aiohttp, shouldn't really matter in this case

pliant gulch
#

There is probably a project on GitHub that does telegram-discord bridging

#

You could probably just do a git clone and edit some configs

wild spoke
#

But it does not work for some reason

#

it sees the message being sent, but gives a traceback

pliant gulch
#

Id just suggest looking for more repos, one of them will eventually work

wild spoke
#

lets see if it works

wild spoke
#

Traceback (most recent call last):
  File "C:\Users\Kastle\Desktop\telebagger\telelooper.py", line 52, in <module>
    result = tclient(GetDialogsRequest(
TypeError: __init__() missing 1 required positional argument: 'hash'

(base) C:\Users\Kastle\Desktop\telebagger>
vale wing
wild spoke
#

but still gives me a traceback

#
Connecting to Telegram...
C:\Users\Kastle\Desktop\telebagger\telelooper.py:43: RuntimeWarning: coroutine 'TelegramBaseClient.connect' was never awaited
  tclient.connect()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\Kastle\Desktop\telebagger\telelooper.py:44: RuntimeWarning: coroutine 'UserMethods.is_user_authorized' was never awaited
  if not tclient.is_user_authorized():
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "C:\Users\Kastle\Desktop\telebagger\telelooper.py", line 52, in <module>
    result = tclient(GetDialogsRequest(
TypeError: __init__() missing 1 required positional argument: 'hash'
vale wing
#

Eh that's why it's better to build your own application

wild spoke
#

(almost zero)

vale wing
#

I never use API wrappers for a couple requests

vale wing
#

HTTP interactions are VERY complicated to beginners

wild spoke
#

I literally wanted to add a bot that fetches jokes from tg channel

vale wing
#

Don't public ones exist

slate swan
#

import os
import discord

bot = discord.Client()
intents = discord.Intents.default()
intents.members = True
token = ""

async def on_ready():
print ("Ready")

@bot.event
async def on_voice_state_update(member, before, after):
targetID = ("921082510471987261")

if before.channel is None and after.channel is not None and member.id == targetID.id:
    await member.voice.channel.connect()

bot.run(token)
looking to make if someone joins a VC the bot joins as well ^

vale wing
#

!code please

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.

junior verge
#

!code

nocturne ridge
#

any tips on how I can make economy?

vale wing
#

And yeah if you would ever want to add commands to your bot use commands.Bot (discord.Client triggers me although it is ok to use it if it only listens for events)

slate swan
#
import discord

bot = discord.Client()
intents = discord.Intents.default()
intents.members = True
token = ""




async def on_ready():
  print ("Ready")

@bot.event
async def on_voice_state_update(member, before, after):
    targetID = ("921082510471987261")

    if before.channel is None and after.channel is not None and member.id == targetID.id:
        await member.voice.channel.connect()

bot.run(token)```
vale wing
slate swan
vale wing
#

!d discord.on_voice_state_update

unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
nocturne ridge
#

what about playing a youtube video in a voice chat? how can I make it?

vale wing
#

I remember something about this event was changed in 2.0

nocturne ridge
#

no like music

slate swan
#

@vale wing could you help me code that function please

vale wing
#

Usually people use ytdl for that and it breaks youtube ToS

vale wing
#

And I think I just did

#
targetID = ("921082510471987261")

    if before.channel is None and after.channel is not None and member.id == targetID.id:
        await member.voice.channel.connect()```
One question - wtf
#

Sorry might sound offensively but those ID comparisons make no sense

#
  1. member.id is int and your targetID is str, objects of different types will never be equal
  2. How does targetID have id attribute
  3. What for do you need brackets in targetID declaration
slate swan
vale wing
#

Fixed code would look like this

target_id = 92108251047198726
if after.channel is not None and member.id == target_id:
    await member.voice.channel.connect()```
And yeah I don't think it is necessary to check if `before.channel is None` cause if the user moves from channel to channel, bot won't follow them (maybe you want to implement that idk)
wild spoke
#

new traceback

Traceback (most recent call last):
  File "C:\Users\Kastle\Desktop\telebagger\telelooper.py", line 61, in <module>
    for p in result.chats:
AttributeError: 'coroutine' object has no attribute 'chats'
sys:1: RuntimeWarning: coroutine 'UserMethods.__call__' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
vale wing
#

How did you get result

wild spoke
#

I added hash value

vale wing
#

Doesn't really matter just await the function that returns result

wild spoke
#

somewhere here

for p in result.chats:
    if type(p) is Channel:
        print(str(p.id)+": "+p.title)
        if p.id == channel_id:
            channel_name = p.title
            print(p.stringify())
            chan_type = 'channel'
for u in result.users:
    print(str(u.id)+": "+u.first_name)
    if u.id == channel_id:
        channel_name = u.first_name
        print(u.stringify())
        chan_type = 'user'
vale wing
#

And yeah this is kinda out of topic now, not a discord bot

vale wing
wild spoke
#
result = tclient(GetDialogsRequest(
                 offset_date=last_date,
                 offset_id=0,
                 offset_peer=InputPeerEmpty(),
                 limit=chunk_size,
                 hash=0
             ))
pp.pprint(result)
warped mirage
#
@client.event
async def on_member_join(member):
    embed = discord.Embed(colour=0x00008B, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
    embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
    embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
    embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
    embed.set_thumbnail(url=f"{member.avatar.url}")
    embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
    embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
    embed.timestamp = datetime.datetime.uctnow()

    channel = await client.get_channel(id=944574345416671313)

    await channel.send(embed=embed)``` guys this event does not return a error or respond
heady sluice
#

get_channel is not a coro

#

you don't need await for get_channel

warped mirage
#

what shall i do

vale wing
heady sluice
#

remove await from get_channel

vale wing
#

And yeah this is no longer discord bots related issue

warped mirage
#

channel = client.get_channel(id=944574345416671313) so just this?

heady sluice
#

and id is not a kwarg

#

iirc it's pos only

vale wing
#

Sussy code

warped mirage
#

should i remove the id

heady sluice
#

!d discord.Client.get_channel

unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
wild spoke
heady sluice
#

it's positional only

#

remove id=

warped mirage
#

ok

vale wing
# wild spoke ?

Ight man sorry I cannot help if you don't know the basics of python

heady sluice
#

yes you can

vale wing
#

Maybe await is not that basic but that is too easy to understand

vale wing
#

And giving the code to copypaste

warped mirage
heady sluice
#

perhaps error handler

#

?

warped mirage
#

im on 2.0 btw if that matters

heady sluice
#

not really

warped mirage
#
@client.event
async def on_member_join(member):
    embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
    embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
    embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
    embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
    embed.set_thumbnail(url=f"{member.avatar.url}")
    embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
    embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
    embed.timestamp = datetime.datetime.uctnow()

    channel = client.get_channel(944574345416671313)

    await channel.send(embed=embed)``` idk tbf
odd mango
#

which free hosting service can handle high user traffic?

heady sluice
#

do you have an on_command_error

#

or on_error

warped mirage
heady sluice
#

member intents? probably yes

vale wing
warped mirage
#

hmm lemme check

vale wing
#

DigitalOcean is free for like 2 months

#

AWS is free for like 1 year

warped mirage
warped mirage
vale wing
#

Nah

odd mango
#

AWS ah, i dont know how to host bots over there... how much ram and disk space dors AWS offer anyways

warped mirage
#

750 hours to be exact for hosting

heady sluice
vale wing
sick birch
#

You get to choose what you need for your purposes and scale it up as needed

warped mirage
#
@client.event
async def on_member_join(member):
    embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
    embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
    embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
    embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
    embed.set_thumbnail(url=f"{member.avatar.url}")
    embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
    embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
    embed.timestamp = datetime.datetime.uctnow()

    channel = client.get_channel(944574345416671313)

    await channel.send(embed=embed)``` anything wrong here?
odd mango
#

oh sick

vale wing
#

Depends bots of what scale you host might be enough might be not

sick birch
#

Good thing is, say your bot grows, and you need more RAM, you can just upgrade without having to do anything special like setting up the bot again

#

It goes all the way up to ~400gb ram I believe

heady sluice
#

but not one thing that could cause this to not work

sick birch
#

It's a "use what you need, upgrade as necessary" philosophy

vale wing
odd mango
warped mirage
sick birch
heady sluice
odd mango
#

f

vale wing
#

Imagine discord bot rendering fractals in real time

warped mirage
#

So my bot won’t work anymore ? Lol

heady sluice
#

do you overwrite on_member_join

odd mango
warped mirage
heady sluice
#

(do you have multiple on_member_join events)

vale wing
sick birch
vale wing
#

The free tier is 1 gb I believe

odd mango
#

whats the free cap

#

oof only if it was 2

sick birch
#

As for actually hosting, not very difficult. Clone your repo from github, python3 main.py or whatever your main file is, easy. I'd suggest dockerizing it however

#

Then you just need docker-compose up and set everything you need up

vale wing
#

I just docker run

odd mango
#

you use aws?

vale wing
#

with tons of -e flags don't mind

sick birch
#

I do, yes

warped mirage
sick birch
warped mirage
#

Not that I know of

vale wing
sick birch
#

so i don't have to specify hundreds of flags

heady sluice
#

if only that would've been it

warped mirage
#

I have a on_ready event but I doubt that causes anything

unkempt canyonBOT
#

.github/workflows/runner.yml line 35

run: docker run -d --name aias --net=host -v /home/exenifix/aias/logs:/app/logs -v /home/exenifix/aias/models:/app/ai/models -e TOKEN=$TOKEN -e DATABASE=$DATABASE -e HOST=$HOST -e USER=$USER -e PASSWORD=$PASSWORD -e TOPGG_TOKEN=$TOPGG_TOKEN aias:latest```
odd mango
warped mirage
#

Any scopes I gotta select? When adding the bot

warped mirage
heady sluice
#

nop

sick birch
#

Because both are pretty easy and you can figure it out yourself with minimal effort

warped mirage
odd mango
#

i am looking for what to do after i save my file from pycharm 😂

heady sluice
#

you can add a debug print statement to the start of the event to see if the code launches

vale wing
heady sluice
#

just add a print

#

to the start

heady sluice
#

under async def on_member_join

vale wing
warped mirage
#

So print() and what inside ?

heady sluice
#

anything you want

vale wing
#

Not even with docker

heady sluice
#

see if it prints

warped mirage
#

Ok

heady sluice
#

if it prints, the problem is inside on_member_join

#

else it's outside of it

odd mango
#

512 mb ram lmao

vale wing
#

Heroku is blocked in russia so I have no idea

odd mango
#

ohh

heady sluice
#

you didn't lose much

vale wing
#

512 seems smol

sick birch
#

Heroku is not ideal for discord bots, I'd stay away if I can

odd mango
#

oh

vale wing
#

I can actually put your bot on my server if it doesn't cause really high load

sick birch
#

Usually the OS is the heaviest

vale wing
#

I mean for bots

sick birch
#

Yeah, the bot itself is not a big deal

warped mirage
#

@heady sluice the thing hasnt printed when i started the bot

sick birch
#

it's I/O so I doubt it's going to being memory intensive or anything

heady sluice
#

wdym when you started the bot

vale wing
warped mirage
#

alr lemme see

vale wing
#

Some flag to docker ps or smth

sick birch
#

I know there's a way, but not sure how myself

vale wing
#

Ok docker stats found it

#

@sick birch well first 2 bots consume 200 mb

sick birch
#

Ah, surprising

vale wing
#

1st is AI bot for antispam which is in 50 guilds

#

As for second I have no idea why tf it eats 200 mb

#

It is in 1 guild and doesn't do much

sick birch
vale wing
#

Lol

regal pulsar
#

lol

heady sluice
#

ol

warped mirage
#
 File "C:\Users\Dom\Desktop\ZEEFUT UTILITIES\main.py", line 27, in on_member_join
    embed.timestamp = datetime.datetime.uctnow()
AttributeError: type object 'datetime.datetime' has no attribute 'uctnow'``` @heady sluice any ideas?
vale wing
#

Typo

#

It's utcnow

warped mirage
#

Lmao

heady sluice
#

where did the error come from

livid hinge
heady sluice
#

you had an on_error didn't u

#

@warped mirage I have to knowpeepocry

livid hinge
warped mirage
heady sluice
#

what

warped mirage
#

Lol

heady sluice
#

this is next level shit

#

but I can't ask that to people when I try helping them

livid hinge
#

also no output = oh yeah i did have on_error lmao

heady sluice
#

I'll let it slide

heady sluice
livid hinge
#

or no intents

heady sluice
#

I asked that

#

I asked almost everything that could've happened

#

I didn't ask what happened or if he made sure the bot was running

livid hinge
#

i didnt mean you didn't

heady sluice
#

maybe I should write these in a protocol

#
  1. ask for eh
  2. ask for intents
  3. ask for possible overwrites
  4. ask if the bot is running
  5. ask if the bot is in the server
#
  1. say you have no idea
livid hinge
#
  1. computer is turned off
heady sluice
#

well

#

that's on a higher level than my genius

livid hinge
#

that's not a bad checklist to have in a tag or smth

#

i leave it to an enterprising individual to wtite up and make the pull request

heady sluice
#

@ Ashley we have a job for you

livid hinge
#

and create a github issue

#

lol thats so much work

heady sluice
#

but different events have different checklists

#

so yeah

livid hinge
#

random message command

heady sluice
#

hard

livid hinge
#

is @ Ashley looking for smth to do

#

lmao

warped mirage
#
@client.event
async def on_member_join(member):
    
    embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
    embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
    embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
    embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
    embed.set_thumbnail(url=f"{member.avatar.url}")
    embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
    embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
    embed.timestamp = datetime.datetime.utcnow()

    channel = client.get_channel(944574345416671313)

    await channel.send(embed=embed)``` how can i add so it @ the person at the top , but not in a embed
heady sluice
#

await channel.send(message.author.mention, embed=embed)

tidal hawk
#

that bot is a group project

heady sluice
#

sus

#

@warped mirage you still have so many f-stringspeepocry

warped mirage
heady sluice
#

yes

warped mirage
#

Alright

#

After this one more thing

heady sluice
#

the first positional argument is the content

tidal hawk
#

why not try it yourself xd

warped mirage
#

TICKET SYSTEM D_die

heady sluice
#

good luck

#

I'm dead

warped mirage
#

Ashley lmao I thought u left this server

#

I couldn’t ping u at all

heady sluice
#

I'm so dead

slate swan
slate swan
heady sluice
#

she did not see it

slate swan
#

I'd rather pretend I didn't, dw

heady sluice
#

let's pretend this channel isn't here

slate swan
#

Let's pretend we don't exist.

vocal plover
#

wdym pretend, I dont exist

slate swan
#

no comments now

heady sluice
#

you guys suck at pretending this channel isn't here

slate swan
#

Robin lurking
||Don't react with a hand wave sign or eyes||

heady sluice
#

imagine being able to react

wild spoke
#

so, I summed up that the issue is here:

channel_1 = discord_client.get_channel(config["discord_1_channel"])


    if 'Mario' in message:
        await channel_1.send(message)

    quit()
#

removing "quit()" just make script freeze on standby without sending anything

#

"message" is being pulled from here

message = sys.argv[1]
#

which is pulled from another script somewhere here


            # This is probably not the best way to do this but definitely the easiest way. 
            # When message triggers you start discord messanger script in new thread and sends parsed input as sys.argv[1]
            subprocess.call(["python", "discord_messager.py", str(parsed_response)])
            # this will forward your message to channel_recieve in Telegram
            await client.forward_messages(output_channel, event.message)  

    client.run_until_disconnected()

''' 
------------------------------------------------------------------------
          MAIN FUNCTION - Can't dream without a brain ...
------------------------------------------------------------------------
'''

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} {{CONFIG_PATH}}")
        sys.exit(1)
    with open(sys.argv[1], 'rb') as f:
        config = yaml.safe_load(f)
    start(config)
tidal hawk
#

what is that

wild spoke
#

Telegram to discord forwader

#

I've been trying 4 different scripts for the past 4 hours and nothing works

#

This one is closest to be working

tidal hawk
#

oh okay

#

freelancing huh

wild spoke
#

No, trying to add a custom bot for the server

#

using open source scripts

tidal hawk
#

I'm just randomly guessing but, is that possible:

You create a on_message like listener in telegeram and then post every new message to Discord via Python requests?

wild spoke
#

idk how the coder did it

#

im just watching it with crossed eyes and trying to understand the code with knowledge of 1st course student

#

and maaan. English...

warped mirage
#
@client.event
async def on_member_join(member):
    message = message.author
    embed = discord.Embed(colour=0xFF00FF, description=f"Welcome to ZEEFUT {member.name}. The current member count is {len(list(member.guild.members))}", timestamp=datetime.datetime.utcfromtimestamp(1553629094))
    embed.add_field(name="How to begin?", value=f"Start of by reading [#944591911426068570](/guild/267624335836053506/channel/944591911426068570/) to be sure you don't make mistakes!")
    embed.add_field(name="Main Channels", value=f"[#951379876844281947](/guild/267624335836053506/channel/951379876844281947/) [#944574345416671313](/guild/267624335836053506/channel/944574345416671313/) [#944590565679460372](/guild/267624335836053506/channel/944590565679460372/)")
    embed.add_field(name="Wanna apply for staff?", value=f"do ;apply in [#945396834128511056](/guild/267624335836053506/channel/945396834128511056/) , good luck getting accepted!")
    embed.set_thumbnail(url=f"{member.avatar.url}")
    embed.set_author(name=f"{member.name}", icon_url=f"{member.avatar.url}")
    embed.set_footer(text=f"{member.guild}", icon_url=f"{member.avatar.url}")
    embed.timestamp = datetime.datetime.utcnow()

    channel = client.get_channel(944574345416671313)

    await channel.send(message.author.mention, embed=embed)``` guys how do i fix this
tidal hawk
#

Okay, well i guess that my idea is really good.. You just have to find out how to listen to messages in Telegram

warped mirage
# tidal hawk What's the error

File "C:\Users\Dom\Desktop\ZEEFUT UTILITIES\main.py", line 20, in on_member_join
message = message.author
UnboundLocalError: local variable 'message' referenced before assignment

#

its meant to ping the member

tidal hawk
#

bruh

#

just use member.mention instead of message.author.mention xd

wild spoke
#
_ClientEventTask exception was never retrieved
future: <ClientEventTask state=finished event=on_ready coro=<function on_ready at 0x000001B9F46781F0> exception=SystemExit(None)>
Traceback (most recent call last):
  File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 698, in run
    loop.run_forever()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 601, in run_forever
    self._run_once()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 1905, in _run_once
    handle._run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\asyncio\events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "C:\Users\Kastle\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Kastle\tg2ds\discord_messager.py", line 46, in on_ready
    quit()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\_sitebuiltins.py", line 26, in __call__
    raise SystemExit(code)
SystemExit: None
tidal hawk
wild spoke
#

and it's something with

quit()
#

if only I knew what exactly

keen mural
#

Where can i go to learn slash commands on d.py 2.0

tidal hawk
#

check out examples on github

wild spoke
#
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} {{CONFIG_PATH}}")
        sys.exit(1)
    with open(sys.argv[1], 'rb') as f:
        config = yaml.safe_load(f)
    start(config)

the problem is 100% somewhere here

tidal hawk
#

why do you think that

wild spoke
#

because it crashes as soon as it gets there

#

but still points at

quit()
tidal hawk
#

I think you should try to create a code for that by yourself

wild spoke
#

with zero skills

tidal hawk
#

oh well

#

time to start learning then

wild spoke
#

I will learn as soon as it starts working as intended

tidal hawk
#

Well that's not possible without spoon feeding

wild spoke
#

I need a working example to see

tidal hawk
#

Send the on_ready part

wild spoke
#

async def on_ready():

    print('Есть контакт с пользователем {0.user}'.format(discord_client))
    print('Ждем сообщения')

    # My channels are for RTX card drops and PS5
    channel_1 = discord_client.get_channel(config["discord_1_channel"])


    if 'Mario' in message:
        await channel_1.send(message)

    quit()

discord_client.run(config["discord_bot_token"])

tidal hawk
#

why is there a quit there?

wild spoke
#

i dont know

#

but without it, it just won't work

#

stuck on printing

mossy jacinth
#

Hey is it possible for a modal, to have the Server invite of the Current server as placeholder? using nextcord

wild spoke
#
(base) C:\Users\Kastle\tg2ds>python3 forwardgram.py config.yml
2022-06-12 01:10:29,478 - root - INFO - Listening on 1 channels. Forwarding messages to 1 channels.
2022-06-12 01:10:30,953 - root - INFO - Message Was: Message(id=27, peer_id=PeerChannel(channel_id=1652994913), date=datetime.datetime(2022, 6, 11, 22, 9, 56, tzinfo=datetime.timezone.utc), message='П', out=True, mentioned=False, media_unread=False, silent=True, post=True, from_scheduled=False, legacy=False, edit_hide=False, pinned=False, from_id=None, fwd_from=None, via_bot_id=None, reply_to=None, media=None, reply_markup=None, entities=[], views=1, forwards=0, replies=None, edit_date=None, post_author=None, grouped_id=None, restriction_reason=[], ttl_period=None)
Got in contact with Юморист#1311
Awaiting for message...
#

Launched without quit()

tidal hawk
#

well it's awaiting for message

wild spoke
#

and its stuck here

tidal hawk
#

does something happen when you type?

wild spoke
#

i send message in tg

#

and it stops forwarding it to another channel (like intended in telegram script)

#

that means the program is stuck on discord script, looping without

quit()
#

stucks here

 channel_1 = discord_client.get_channel(config["discord_1_channel"])


    if 'Mario' in message:
        await channel_1.send(message)
#

also

#

I dont know why this dude included "mario"

tidal hawk
#

remove it xd

wild spoke
#

like what it does? check if "Mario" presents in message?

wild spoke
#

Will it work if I use it like that?

if '' in message:
        await channel_1.send(message)
tidal hawk
#

just remove the if part

#
 channel_1 = discord_client.get_channel(config["discord_1_channel"])
 await channel_1.send(message)
wild spoke
#

HOLY SHIT IT WORKED

tidal hawk
#

LOL

#

congrats XD

wild spoke
#

Ok it forwards the message but does not listen to the next one

tidal hawk
#

because it quits i think

wild spoke
#

no, it freezes

#

When the script detects new message, he prints it on the console like that

2022-06-12 01:16:03,411 - root - INFO - Message Was: Message(id=32, peer_id=PeerChannel(channel_id=1652994913), date=datetime.datetime(2022, 6, 11, 22, 15, 29, tzinfo=datetime.timezone.utc), message='Е', out=True, mentioned=False, media_unread=False, silent=True, post=True, from_scheduled=False, legacy=False, edit_hide=False, pinned=False, from_id=None, fwd_from=None, via_bot_id=None, reply_to=None, media=None, reply_markup=None, entities=[], views=1, forwards=0, replies=None, edit_date=None, post_author=None, grouped_id=None, restriction_reason=[], ttl_period=None)
#
message='Е'
keen mural
wild spoke
#

Thats where you need a

quit()
slate swan
wild spoke
#

Well, telegram script waits for the message, sends it to discord script which send it to channel using bot and then it should go back to telegram

flat solstice
#

Hi so I'm trying to name my logs file as my bots username but it keeps getting named None ```py
bot = Zupie()

recipients = Config().RECIPIENTS.strip(" ").split(",")

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()

logger.setLevel(logging.DEBUG)

file = logging.FileHandler(filename=f"{bot.user}.log", encoding="utf-8", mode="w")```

slate swan
#

bot.user gets initialised only after the bot is running, and you're doing it before it runs

flat solstice
#

ah, ofc

flat solstice
quaint epoch
#

nice

tough bobcat
#

is there any way to include the full traceback in the on_command_error?

#

because this is all the information i can seem to get without the line number and such

unkempt canyonBOT
#

discord/ext/commands/bot.py line 328

traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)```
slate swan
#

instead of printing it, like it's doing here
send it

tough bobcat
#

oh wow ok

#

i will take a look, ty

flat solstice
#

it might not be the best way tho

slate swan
#

does anyone know how to fix this

#

!indents

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

slate swan
karmic marsh
#

question...

#

Command raised an exception: ValueError: components must be a WrappedComponent or ActionRow, a sequence/list of WrappedComponents or ActionRows, or a nested sequence/list of WrappedComponents

#

just trying to embed a disnake.ui.button in a inter.response.send_message

boreal ravine
#

ui.button is the decorator

karmic marsh
#

ah, yup

#

that was just a typo though lol

#

the issue is that I can't have self without making the UI a separate class

#
class UI(disnake.ui.View):
    def __init__(self, inter): # note the 'self' here
        super().__init__()
        self.add_item(CancelButton(self, inter))
async def test(inter):
        await inter.send(view=UI(inter))

this works

#

but I can't do this:

async def test(inter):
        await inter.send(view=disnake.ui.View().add_item(CancelButton(self, inter)))
#

because self doesn't work in that context

#

here's how the button is implemented:

class CancelButton(disnake.ui.Button):
    def __init__(self, view, inter):
        self.par_view = view
        self.par_inter = inter
        super().__init__(label="Cancel", style=disnake.ButtonStyle.grey)
    async def callback(self,inter):
        await self.par_inter.edit_original_message("Cancelled", view=None)
        self.par_view.stop()
slate swan
#

How do I check a person has changed pfp? I'm trying before.display_avatar.url != after.display_avatar.url but doesn't seem to work.

karmic marsh
#

what is the event you're subscribing to

slate swan
sick birch
#

If you have the right intents enabled, then yes your bot can pick up status updates through that event

fading marlin
#

display_avatar returns an Asset, which you can compare

slate swan
fading marlin
#

!d discord.Asset

unkempt canyonBOT
#

class discord.Asset```
Represents a CDN asset on Discord.

str(x) Returns the URL of the CDN asset.

len(x) Returns the length of the CDN asset’s URL.

x == y Checks if the asset is equal to another asset.

x != y Checks if the asset is not equal to another asset.

hash(x) Returns the hash of the asset.
karmic marsh
fading marlin
fading marlin
slate swan
#

!disnake.on_user_update

#

!d disnake.on_user_update

unkempt canyonBOT
#

disnake.on_user_update(before, after)```
Called when a [`User`](https://docs.disnake.dev/en/latest/api.html#disnake.User "disnake.User") updates their profile.

This is called when one or more of the following things change:

• avatar

• username

• discriminator...
karmic marsh
#

I'd like to attach a disnake.ui.Button to a response

slate swan
fading marlin
karmic marsh
#

uhh... I think so?

#

not really 'another'

fading marlin
karmic marsh
#

yeah... that much works

fading marlin
#

View doesn't take any params, unless disnake changed that

karmic marsh
#

correct

#

that's not the issue

slate swan
karmic marsh
#

look at how the disnake.ui.Button is implemented

#

it needs view and inter

#

if I just do py await inter.send(view=disnake.ui.View().add_item(CancelButton(inter)))

#

I get this error:

#

Command raised an exception: TypeError: CancelButton.init() missing 1 required positional argument: 'inter'

fading marlin
#

why do disnake docs have to be so slow blobpain

karmic marsh
#

because it needs two

slate swan
karmic marsh
#

it needs to be like this:

await inter.send(view=disnake.ui.View().add_item(CancelButton(view, inter))) # 'view' param
karmic marsh
slate swan
#

!d disnake.ui.Button.view cause it already exists.

unkempt canyonBOT
slate swan
#

you don't do that manually!

karmic marsh
#

I'm passing in the parent's view

slate swan
#

thats what it is.

karmic marsh
#

I could call that anything I want

fading marlin
karmic marsh
#

yeah... except I need it lmao

#

for this:

self.par_view.stop()
slate swan
#

you can just do self.view.stop() but okay

karmic marsh
#

not the parent's view

#

if this makes more sense to you:

class CancelButton(disnake.ui.Button):
    def __init__(self, pview, inter):
        self.par_view = pview
        self.par_inter = inter
slate swan
#

wdym by parent view, the view which has the button right?

karmic marsh
#

it's not the same as the view of the disnake.ui.Button

slate swan
#

thats exactly it.

karmic marsh
#

no no wait

#

the view of the view which has the button

slate swan
#

wot?

karmic marsh
#

I think?

slate swan
#

a view does not have a view inside it

karmic marsh
#

all I know is that just using the view of the button does not work

#

let me confirm that rq

slate swan
#

why don't you try it and see before making up things yourself, testing 1 thing in a second is better than arguing over it for minutes

karmic marsh
#

idk, I was having a lot of issues with this yesterday

#

and this was the solution that worked

#

I'm not saying I didn't do something stupid though lmao

#

alright, I'm just more confused now lol hold on

quaint epoch
#

anyone know why i can't ping my bot?

karmic marsh
#
class CancelButton(disnake.ui.Button):
    def __init__(self, inter):
        self.par_inter = inter
        super().__init__(label="Cancel", style=disnake.ButtonStyle.grey)
    async def callback(self,inter):
        await self.par_inter.edit_original_message("Cancelled", view=None)
        self.view.stop()
@commands.slash_command()
async def button(inter):
    """Sends a button."""
    await inter.send(view=disnake.ui.View().add_item(CancelButton(inter)))

Command raised an exception: AttributeError: 'NoneType' object has no attribute 'to_components'

shrewd apex
slate swan
# shrewd apex u know any good SQL tutorial for group by and joins?
#

tho its mysql, but thats same for all types of sql

shrewd apex
#

ic

#

thx

karmic marsh
#

uh

#

I'm sure that I did

slate swan
#
view = ui.View()
view.add_item(...)
await send(view= view)
``` you don't use add_item inside that send part lol
karmic marsh
#

huh

#

okay

#

I'm used to c# where that would work just fine

#

so is there any way to condense it into a one-liner or not really?

slate swan
#

not in a non-estoric way since add_item returns None

karmic marsh
#

hmm, okay

#

guess I'll have to just wrap my head around doing things the python way lol

desert cosmos
shrewd apex
#

apparently not they look like hieroglyphs to me

desert cosmos
#

well they didn't give full context, how can someone ping bot in hieroglyphs 🙃

#

or worst code in hieroglyphs

karmic marsh
#

They're wingdings lol

heady citrus
#

whats the max a discord server can have of channels

slate swan
#

50 categories, 500 channels

naive parcel
#

any replit users here?

upbeat vigil
#

anyone know how to keep a repl on 24/7?

slate swan
#

you would use keep_alive and flask iirc, but you really shouldnt

paper sluice
#

.topic

lament depotBOT
#
**What feature would you like to see added to the library? What feature in the library do you think is redundant?**

Suggest more topics here!

slate swan
#

and other can use it

slate swan
slate swan
slate swan
#

um ok

vocal snow
#

wtf

slate swan
#

the first if statement will always be false and why hard code it?

#

you can just do

#

!e

print(f"hello {__import__('random').randint(1, 10) * 'world '}")
unkempt canyonBOT
#

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

hello world world world world world world world world 
dim sentinel
#

it's from a list

#

it would take a value from the list right?

slate swan
#

how much max buttons can i add per view

unkempt canyonBOT
#

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

False
slate swan
slate swan
#

depends on your message width too iirc

#

never knew that actually

slate swan
dim sentinel
#

i wanted my code to be bit like this

slate swan
#

youre literally doing int == list

slate swan
dim sentinel
slate swan
#

if so you would use the in keyword

slate swan
slate swan
slate swan
#

!d in

unkempt canyonBOT
#
in

6.10.2. Membership test operations

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s. All built-in sequences and set types support this as well as dictionary, for which in tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).

For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

dim sentinel
slate swan
atomic sierra
#

Hey guys, I want to create a discord bot and this is my first time. Can someone tell me on how to go about it?

slate swan
#

and how much row can i add?

paper sluice
slate swan
slate swan
#

you would use a task

#

yep

#

yeah thats what i would do

#

is their any time frame limitation not sure, doubt it

#

you can probably just check with seconds and then try it with hours

dim sentinel
#

holy

#

even if

slate swan
#

this is so hard coded, why?

dim sentinel
#

but what did i do wrong this time

slate swan
#

maybe ask in the dpy server

dim sentinel
slate swan
dusky pine
#

Python will check if "8D" is in the responses list first

#

which, it will always be

paper sluice
#

👀 whats going on here

dusky pine
#

unless a butterfly comes in and flips a bit that causes it to not

dusky pine
#

pp 🙂

dim sentinel
#

so what can i do to resolve this

slate swan
dusky pine
#

yeah, store the pp length in a variable

#

then create another variable for the embed color, if it's long then make it green, red if short

slate swan
#

!e

print(f"hello {2 * 'world '}")
unkempt canyonBOT
#

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

hello world world 
dim sentinel
dim sentinel
slate swan
#

!d random.randint

unkempt canyonBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
dusky pine
#
pp_length = random.randint(0, 30)

color = None
if pp_length > 20:
    color = discord.Color.green()
else:
    color = discord.Color.red()

pp_string = f"8{'=' * pp_length}D"
#

something like that, then create the embed from those values

#

i've spoonfed again have i

paper sluice
#

:yes:

slate swan
#

color = discord.Color.green() if (l:=random.randint(0, 30)) > 20 else discord.Color.red(); string = f"ok{'sus' * l}ok" lemon_smirk

dusky pine
#

you monster

slate swan
#

im sorry😔

paper sluice
slate swan
#

using list indexing with true values i see

dim sentinel
# dusky pine ```py pp_length = random.randint(0, 30) color = None if pp_length > 20: col...
@spi.command()
async def pp(ctx):
    size= random.randint(0, 9)



    color = None
    if size> 5:
        embul=discord.Embed(title="PP calculator",color=discord.Color.red())
        embul.add_field(name=f"Your pp length\n{random.choice(response)}",value="This is not a random response.")
        await ctx.channel.send(embed=embul)

    else:
        embul=discord.Embed(title="PP calculator",color=discord.Color.red())
        embul.add_field(name=f"Your pp length\n{random.choice(response)}",value="This is not a random response.")
        await ctx.channel.send(embed=embul)
  
    pp_string = f"8{'=' * size}D"
``` something like this?
dusky pine
#

wait no

#

you're not using pp_string at all

paper sluice
dusky pine
#

ah yeah

#

the tuple trick

slate swan
#

no

dusky pine
#

works 90% of the time

slate swan
#

wait

#

ryuga it doesnt need to be a tuple does it?

paper sluice
#

u mean the (), i dont think so

slate swan
#

im pretty sure a coma is fine or am i just a bit crazy

dim sentinel
dusky pine
paper sluice
dim sentinel
#

it's not even giving any traceback

slate swan
dim sentinel
slate swan
unkempt canyonBOT
#

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

[No output]
dim sentinel
#

i mean it's not giving any te=raceback too

paper sluice
#

:= onlly works in closed spaces

dim sentinel
#

am not using pp_string

paper sluice
#
color,string=(discord.Color.red(),discord.Color.green())[(l:=random.randint(0, 30)) > 20],f"ok{'sus' * l}ok"
slate swan
#

im just confused on an old memory i have where it doesnt use it

#

but youre probably correct so nvm

slate swan