I am trying to fetch messages in real time from some Telegram channels. My code is as follow:
from telethon import TelegramClient, events, sync
import config
client = TelegramClient('anon', config.api_id, config.api_hash)
#client.on(events.NewMessage(chats='channel'))
async def my_event_handler(event):
print(event.raw_text)
The config document contains my credentials. Now this works, except that at some points there are delays of some seconds. And for some channels it completely misses some of the messages if I let the script run long enough. I also use Anaconda.
Is there some workaround to get real time messages without missing any of them?
Related
Is it possible to make a Python program that sends messages in a Discord chat every 2 minutes, but without other users being able to see that it is a program?
You can make a bot to send message every two minutes using the below code
from discord.ext import commands,tasks
#tasks.loop(seconds=120)
async def determine_winner():
message=#Message to be sent
channel_id=#Gives the id of channel where to send
client.get_channel(channel_id).send(message)
If you want to send this message in multiple channel. You should get the id of each channel where the message to be sent and store it in database or json file and fetch it at the time of sending the message.
But self-botting is against discord'sTOS if they found you self-botting they will ban you from discord permanently
My goal is to create a Telegram listener on a specific channel that copies new messages and posts them as tweets on Twitter. So far the python I wrote works well when I run it on my computer, when I send a mock message on my Telegram channel, it detects that a message has been sent, goes down the code, and a tweet is created with the text.
However, this is not the case when I try to run in on an AWS instance (ubuntu).
when running the following code:
import tweepy
from telethon import TelegramClient, events
auth = tweepy.OAuthHandler("", "")
auth.set_access_token("", "")
api = tweepy.API(auth)
print("start")
# Listen to new messages on Telegram Channel
bot = TelegramClient("bot", api_id, api_hash).start(bot_token=bot_token)
with bot:
print("bot-start")
#client.on(events.NewMessage(chats=ChannelURL))
async def newmessagelistener(event):
print("action detected")
client.start()
client.run_until_disconnected()
Things start out ok at the beginning, but then when I write a new test message on the telegram channel - nothing, no "action detected" is returned, only "start" and "bot-start", no tweet is posted.
Any ideas as to what's going on?
Thanks in advance!
I'm trying to use Telethon to download multiple pinned messages from a group using the following code:
from telethon import TelegramClient, types
async def getPinnedMessages():
async with TelegramClient('MySession', api_id, api_hash) as client:
messages = await client.get_messages('MyGroupChat', ids=types.InputMessagePinned())
The problem is that this returns only a single message, even if there are multiple pinned messages. Any suggestions on what I'm missing here? Thanks.
You need to use InputMessagesFilterPinned:
for message in client.iter_messages(chat, filter=types.InputMessagesFilterPinned()):
... # use message
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
I have a problem with discord's bot.
I have done a script which calculate the weather every hour and I want to send the result to discord with bot:
import Secret
import discord
result = "temp is ...."
TOKEN = Secret.BOT_TOKEN
client = discord.Client()
client.send(result)
client.run(TOKEN)
I have searched on google but I have not found an answer to send the result automatically.
Can you help me?
If you're using python just put it in a while loop and have it send the message and sleep for an hour.
for sleep you can import time
Something like:
while true:
client.send(result)
sleep(3600)
Important:
Your bot will be 100% inactive while you sleep it, so if you use it for more than just weather this might not be the solution you're looking for.
Using the time module prevents your bot from doing anything else during the time that it is sleeping.
Use tasks. Just put what you want executed in the task() function:
from discord.ext import tasks
#tasks.loop(seconds=60) # repeat once every 60 seconds
async def task():
pass
mytask.start()