Bot which interacts with telegram bots - python

I was wondering if I can automatically download files from other telegram bots. I've searched online how to make a Python bot (or a Telegram bot written in Python) which do this, but I didn't find anything. Can someone help me?

Interaction between bots in telegram directly isn't possible since the Bot API doesn't support that.
But you can use MTProto libraries to automate almost all interactions with bots (including file downloading). since these libs simply automate regular user accounts, they don't have the limitations of the bot api.
Here is an example to download a file using telethon lib :
from telethon import TelegramClient, events
api_id = <API_ID>
api_hash = '<API_HASH>'
client = TelegramClient('session', api_id, api_hash)
BOT_USER_NAME="#filesending_sample_bot" # the username of the bot that sends files (images, docs, ...)
#client.on(events.NewMessage(func=lambda e: e.is_private))
async def message_handler(event):
if event.message.media is not None: # if there's something to download (media)
await client.download_media(message=event.message, )
async def main():
await client.send_message(BOT_USER_NAME, 'some text or command to trigger file sending') # trigger the bot here by sending something so that the bot sends the media
client.start()
client.loop.run_until_complete(main())
client.run_until_disconnected()
and in my example I created a minimal telegram bot in javascript that sends a photo (as Document) as it receives any message to test the above script out (but you configure the above script to match with your case):
const bot = new (require("telegraf"))(<MY_BOT_TOKEN>);
bot.on("message", (ctx) => ctx.replyWithDocument("https://picsum.photos/200/300"));
bot.launch();
Note that you must connect using a regular telegram account (not using a bot token but rather a phone number) for this to work. If using a telegram bot is a must, you can use the script in the background (by running it as a new process or as a REST api, etc...) and return a result to the telegram bot.

Related

Sending slash command to specific guild channel

this is my first time using python and I've been trying to make a selfbot that would send a slash command to a specific guild channel on startup with discord py for like 5 hours now and I have no idea what I'm doing, does anybody know how to specify a server and channel when sending a message/command or a reliable way to send slash commands that isn't reliant on a discontinued library that doesn't work anymore
I tried going through threads on here aswell as the discord py library to figure out how to do it but I haven't found anything at all
You can get the ID of a channel if you enable Developer Mode in the settings on Discord:
Then you can right click on a channel to copy its ID:
I python you can use discord.py. For example:
import discord
client = discord.Client()
#client.event
async def on_ready():
print('Logged in as', client.user)
channel = client.get_channel(ChannelID)
await channel.send('/command')
await client.close()
client.run('token')
Here you need to replace ChannelID with your channel ID and token with your Discord Bot's token.
If you want to use your account (not recommended) you can pass bot=False in client.run:
client.run('token', bot=False)
To get your account's token, you need to load Discord from a browser (I use Chrome to demonstrate);
Press F12 or Ctrl+Shift+I, to open devtools;
Switch to the Network tab;
Filter the keyword messages;
Open a channel in discord, and a request will be sent to /api/v9/channels/-channel_ID-/messages?limit=50.
Look at that request (click on it, and then switch to Headers tab);
Scroll down to Request headers, and grab your token.

Sending a message to twitch chat doesnt work

I'm creating a simple Twitch bot for personal use. I'm using twitchio.ext commands. Everything works fine, I'm connected, I'm able to print all the messages from the chat, my bot responds to commands but I'm not able to send a message to chat and I don't know why.
from twitchio.ext import commands
class Bot(commands.Bot):
def __init__(self):
super().__init__(token='oauth:censored', prefix='g ', nick = "nick of the bot", irc_token = "censored", initial_channels=['channel'])
async def event_ready(self):
print(f'Using bot as {self.nick}')
#commands.command()
async def test(self, ctx: commands.Context):
await ctx.send('test')
print("printed")
bot = Bot()
#bot.event()
async def event_message(msg):
print(msg.author.name)
print(msg.content)
await bot.handle_commands(msg)
bot.run()
When I type "g test" in chat, the message "test" is not sent but the message "printed" is printed to the console. Do you know where could be the problem? Also, I would like to ask if there is any way how to send a message to chat directly without responding to a command or event.
Try adding the bot as a mod
The 'nick' in the bot init() function doesn't seem to do anything the nick is linked to your IRC username.
I'm assuming the channel in your initial_channels in the init() func isn't actually the channel you put there since you said you were able to type in the chat.
If the channel that you are using the bot from(linked to the oauth key) is not the same channel as you are connecting to in the chat then you probably need to add the bots username as a moderator in that chat
try
/mod [bot_username]
in the chat as the channel owner to do this
Also if your bot is the same account you are sending commands from on twitch the rate limit will be reached unless they are a mod. So either make a dedicated account for your bot or mod the bot on the server

Discord - Send message only from python app to discord channel (one way communication)

I am designing an app where I can send notification to my discord channel when something happen with my python code (e.g new user signup on my website). It will be a one way communication as only python app will send message to discord channel.
Here is what I have tried.
import os
import discord
import asyncio
TOKEN = ""
GUILD = ""
def sendMessage(message):
client = discord.Client()
#client.event
async def on_ready():
channel = client.get_channel(706554288985473048)
await channel.send(message)
print("done")
return ""
client.run(TOKEN)
print("can you see me?")
if __name__ == '__main__':
sendMessage("abc")
sendMessage("def")
The issue is only first message is being sent (i-e abc) and then aysn function is blocking the second call (def).
I don't need to listen to discord events and I don't need to keep the network communication open. Is there any way where I can just post the text (post method of api like we use normally) to discord server without listening to events?
Thanks.
You can send the message to a Discord webhook.
First, make a webhook in the Discord channel you'd like to send messages to.
Then, use the discord.Webhook.from_url method to fetch a Webhook object from the URL Discord gave you.
Finally, use the discord.Webhook.send method to send a message using the webhook.
If you're using version 2 of discord.py, you can use this snippet:
from discord import SyncWebhook
webhook = SyncWebhook.from_url("url-here")
webhook.send("Hello World")
Otherwise, you can make use of the requests module:
import requests
from discord import Webhook, RequestsWebhookAdapter
webhook = Webhook.from_url("url-here", adapter=RequestsWebhookAdapter())
webhook.send("Hello World")
I have found it. "Webhook" is the answer. Instead of using discord.py, just create a webhook for your channle and then just post the data to that endpoint.
import requests
#Webhook of my channel. Click on edit channel --> Webhooks --> Creates webhook
mUrl = "https://discord.com/api/webhooks/729017161942******/-CC0BNUXXyrSLF1UxjHMwuHA141wG-FjyOSDq2Lgt*******************"
data = {"content": 'abc'}
response = requests.post(mUrl, json=data)
print(response.status_code)
print(response.content)
This might be one of the best approaches as it saves the addition of more python packages(one mentioned by #john), but I believe there is a more robust and easy solution for this scenario, as you can add images, make tables and make those notifications look more expressive.
A python library designed for the explicit purpose of sending a message to the discord server. A simple example from the PyPI page would be:
from discord_webhook import DiscordWebhook
webhook = DiscordWebhook(url='your webhook url', content='Webhook Message')
response = webhook.execute()
more examples follow on the page.
This is how the sent notification/message would look like
Discord notification with table

Telegram: Send message to bot from different script

I have a telegram bot that handles user input to perform actions on links that are sent.
In my Telegram Bot I have:
def handle_message(bot, update):
url = update.message.text
# do parsing and add url to database
dispatcher.add_handler(MessageHandler(filters=Filters.text, callback=handle_message))
However I want to also be able to send a URL to the bot from a POST request. i.e. use the telegram bot's API to send a message to itself so it can parse the link.
How can I send a POST request to my telegram bot and have it run handle_message() on the input?
It is technically impossible for bots to communicate with each other (and therefore with themselves).

Sending Discord Messages to external application

I am currently working on a desktop application and I want to get messages sent from Discord to this application. How should I do this?
I have used POST requests and webhooks to send messages TO Discord, but I have never taken messages from a channel and sent them somewhere else.
I know I can do something using on_message like this:
#bot.event
async def on_message(message):
message_content = message.content
## send message_content to external application
I just am confused on what to use/how to send the messages to the application itself. Keep in mind that this I'm making in Python 3.6.6

Categories

Resources