How to simply send a message using discord.py - python

Okay i have a very simple question but i couldnt find out how to solve it by any chance.
I have a script that fetches some numbers out of the steam website, then compares them. i want to use discord.py to send me that results on discord. i already have the bot on discord, but i coulndt figure out how to just send a message and not react to a message sent by a user or anything. This is my code:
Float = float(Float[8:])
if Float <= 0.01:
element2 = driver.find_element_by_xpath('/html/body/div[1]/div[7]/div[2]/div[2]/div[4]/div[1]/div[3]/div[4]/div[4]/div[2]/div[2]/div[2]/span/span[1]')
Price = element2.text
print("Snipe found: \n"
"Mag-7 Carbon Fiber Factory New with Float:\n"
, Float, '\n', Price)
i also have some selenium in it, but that is not a problem. the variable "Float" is also defined before. i simply want to send the stuff that is in the print function as a message to a discord server.
is this possible by any chance?
Thanks for the help

Just make it a command and use ctx.send(). Since you don't know how to send a message on discord.py, I'm assuming that you are very new to it.
import ...
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!')
#bot.command()
async def steamfetch(ctx):
Float = float(Float[8:])
if Float <= 0.01:
element2 = driver.find_element_by_xpath('/html/body/div[1]/div[7]/div[2]/div[2]/div[4]/div[1]/div[3]/div[4]/div[4]/div[2]/div[2]/div[2]/span/span[1]')
Price = element2.text
await ctx.send(f"Snipe found:\nMag-7 Carbon Fiber Factory New with Float:\n{Float}\n{Price}')
You should really look at the discord.py docs or other discord.py tutorials for this because sending a message are in MANY of the discord.py tutorials. I don't know if you did but please try doing your own research before asking a question here.

Related

Send a message in a random channel (discord.py) [duplicate]

This question already has an answer here:
How would I send a message to a random channel?
(1 answer)
Closed 8 months ago.
This post was edited and submitted for review 7 months ago and failed to reopen the post:
Original close reason(s) were not resolved
The setup: I've made a bot to interact with users on my server. One of the features I've added is the game of Marco-Polo. When a user sends "Marco", the bot responds with "POLO...".
The problem: When the bot responds with "POLO...", it responds in the same channel as the original message. I, however, want the bot to respond in a random channel within the server, that sends the user looking for it.
I've searched online for the answer as well as in discord.py, but I haven't been able to find it. However, I'm new to Python and coding altogether, so it could very well be that I am simply missing something or that it's not possible, LOL.
Here is the code for the Marco-Polo game:
#client.event
async def on_message(message):
if message.author == client.user:
return
msg = message.content
time_seconds = 1
if msg.lower() == 'marco':
time_seconds = 5
await asyncio.sleep(time_seconds)
await message.channel.send('POLO...')
message.channel gets the channel that the original message was sent in. Try this code to send in a random channel:
#Get list of all text channels
text_channel_list = []
for channel in message.guild.text_channels:
text_channel_list.append(channel)
#pick random channel and send
channel = random.choice(text_channel_list)
await channel.send('POLO...')
Try this, and let me know if it works. You will need to put import random at the top.
P.S. This should get all channels, which means that if you have some private channels, the bot still might send the message in it. If this will be an issue, we will need to get which channels the user that sent the original message has access to, and only send it in those. Let me know if that is necessary.
Here's a shorter version, using random again:
import random
#random_channel = random.choice(message.channel.guild.channels)
random_channel = random.choice(message.guild.channels)
await random_channel.send("POLO...")
This will send the message in a random channel from all the channels in the guild, including channels it can't send in, for example, StoreChannel, CategoryChannel, etc. (all the channels in the guild: all the GuildChannels, whether Messageable or not)
This probably will work:
random_channel = random.choice(message.guild.textchannels)
await random_channel.send("POLO...")
...as it gets a random channel from all the TextChannels in the guild.
Also, you don't need to install random (like pip install random) as it's a built-in Python package.

How to forward message from a specific chat in Telethon?

This is a continuation of this short forum (How forward message to other contact with telethon).
Problem
I replaced entity with the group id for GC A and it works since I type something in GC B the bot forwards it to GC A however, when I message GC A the bot still forwards the messages to GC A which I don't want, I just want it to not react.
await client.forward_messages(entity, event.message)
The bot forwards every new message because the event type is new messages so I was thinking, is there a way to filter it so that it only triggers when there are new messages on a specific group?
#client.on(events.NewMessage)
async def main(event):
Solutions Ive tried
Looking at the documentation (https://docs.telethon.dev/en/latest/modules/client.html#telethon.client.messages.MessageMethods.forward_messages) there is an example with the argument "from_chat". So I placed the group id of GC B but it doesn't work.
await client.forward_messages(chat, message_id, from_chat)
I also tried making the argument look like this to copy the examples better but It does not work
await client.forward_messages(entity("group ID"), event.message, from_chat("group_id"))
For me worked this code:
#client.on(events.NewMessage(chats = FROM_CHANNEL_ID))
async def main(event):
await event.forward_to(TO_CHAT_ID)
Try it, may it will work for you to.

"ValueError: Could not find the input entity for PeerChannel" with Bot

For the life of me, I can't figure out this one out.
I have created a new Telegram Bot and created a new channel, in which I added my bot as an Admin.
After reading 100 times the docs, I tried to have the entity "seen" somehow but :
get_dialogs() is not allowed for bots
client.get_entity('') is not allowed for bots
Not sure what else to do…
I do have published some messages in the channel.
My code looks something like :
from telethon import TelegramClient
telethon_client = TelegramClient(
api_id=int(config['TELETHON_API_ID']),
api_hash=config['TELETHON_API_HASH'],
session=config['TELETHON_SESSION']
).start(bot_token=config['TELEGRAM_BOT_TOKEN'])
with telethon_client:
telethon_client.loop.run_until_complete(__async_get_users(chat_id))
async def __async_get_users(chat_id):
channel = await telethon_client.get_entity(chat_id) # -100xxxxx
tg_users = await telethon_client.get_participants(channel)
Any help, lead, or idea appreciated !
Ok, so, not sure what lead to the resolution of this issue but I did :
disable group privacy mode in #BotFather as #Lonami advised
Sent other messages in the group
Removed and re-added the bot to the group
I still had the issue, but after clearing the session, it now works OK!
Thanks #Lonami for the help!

discord py - message.mentions "else" makes nothing

I want to get the user that was mentioned in a message and send him a private message. That's working without problems, but now I want to add a message for the case, that the mentioned member is not on the same server.
I searched a lot and try now for over 3 hours to find a solution.
Showcase of the problem: https://youtu.be/PYZMVXYtxpE
Heres my code:
#bot.event
async def on_message(message):
if len(message.mentions) == 1:
membe1 = message.mentions[0].id
membe2 = bot.get_user(membe1)
guild = bot.get_guild(message.author.guild.id)
if guild.get_member(membe1) is not None:
await membe2.send(content=f"you was mentioned in the server chat")
else:
embed2 = discord.Embed(title=f"» :warning: | PING not possible", description=f"not possible")
await message.channel.send(content=f"{message.author.mention}", embed=embed)
await message.delete()
return
The first part is working without problems, but at the "else" part, does the bot nothing. He still posts the message with the "invalid" ping in the chat and just ignores it. What can I do to fix that?
There is an error of design in what you are trying to do.
In Discord, you are not able to mention a user if he is not on that same server, so what you are checking will never work at all, currently your code is pretty much checking if the mentioned user exists, which will always happen unless he leaves the guild at the same time the command is executed.
Say for example, to make your command work you want to mention the user user123, who is in your server, you do the following:
#user123 blablabla
And that works because Discord internal cache can find user123 in your server and it is mentioned, which means that clicking on "#user123" will show us a target with his avatar, his roles or whatsoever.
But if you try to do the same for an invalid user, let's say notuser321:
#notuser321 blablabla
This is not a mention, take for example that you know who notuser321 is but he is in the same server as the bot is. Discord cannot retrieve this user from the cache and it is not considered a mention, just a single string, so not a single part of your code will be triggered, because len(message.mentions) will be 0.
Something that you could try would be using regular expressions to find an attempt to tag within message.content. An example would be something like this:
import re
message = "I love #user1 and #user2"
mention_attempt = re.findall(r'[#]\S*', message) # ['#user1', '#user2']

telegram bot send_message() hangs with HTML text

I am new to Telegram Bot API (python telegram.ext), here is my question: I am trying to send formatted message in reply to received message. For simplicity I removed everything from the code below
mtxt = "<ul><li>line 1</li></ul>"
res = bot.send_message(chat_id=update.message.chat_id, text=mtxt, parse_mode='HTML')
print(res)
Nothing is returned to telegram (no answer from bot) and print() never happens. If I remove 'parse_mode...' clause from the call it works.
I must be fundamentally wrong somewhere... This is very basic staff, what is missing?
There only have limited tags :(
You can use emoji to format, or make a suggestion to Telegram.

Categories