I have a code that can copy a message from one channel to another channel, but this code works only for "NewMessages", how to make this code to send all messages from the channel to another channel?
from telethon import TelegramClient, events
import asyncio
api_id =
api_hash = ''
my_channel_id = -1001247324182
channels = [-100129537617]
client = TelegramClient('myGrab', api_id, api_hash)
print("GRAB - Started")
#client.on(events.NewMessage(chats=channels))
async def my_event_handler(event):
if event.message:
await client.send_message(my_channel_id, event.message)
client.start()
client.run_until_disconnected()
So, it is possible to do this code to send all messages from the channel? Maybe, another library?
You can iter_messages and forward it to new channel
Related
I'd imagine this should be a property of a channel but the channel doesn't have anything related to the connection configuration.
You can set the request timeout like this:
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import service_pb2_grpc, service_pb2
stub = service_pb2_grpc.V2Stub(ClarifaiChannel.get_grpc_channel())
if __name__ == '__main__':
YOUR_CLARIFAI_API_KEY = 'addyourclarifaikeyhere'
auth_metadata = (('authorization', f'Key {YOUR_CLARIFAI_API_KEY}'),)
resp = stub.ListModels(service_pb2.ListModelsRequest(),
metadata=auth_metadata,
timeout=0.0001)
print(resp)
Looking at the list of configurations for a grpc channel, there doesn't seem to be a global connection timeout.
I was wondering if there is a possible way to get messages from the telegram channel knowing that I logged in to this account and I am the admin of this channel so I just want the get messages.
import feedparser
from telegram import Update, ForceReply, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, CallbackQueryHandler
from bs4 import BeautifulSoup
from datetime import datetime
import json
import telegram
from time import sleep
from telegram.ext import MessageHandler, Filters
class Config:
def __init__(self):
with open("config.json", "r") as config:
self.config = json.load(config)
class TelegramBotChannel:
def __init__(self, token, start_channel_id):
self.updater = Updater(token=token, use_context=True)
self.dispatcher = self.updater.dispatcher
self.start_channel_id = start_channel_id
if __name__ == '__main__':
telegram_bot = TelegramBotChannel(Config().config["token"], Config().config["start"])
pass
This is the minimal code to fetch the messages from a channel using a telegram bot which is the subscriber (only admin subscription possible) of the channel. Provide the correct bot api as KEY.:
from api_keys import bot_api_key as KEY
from telegram.ext import Updater, Filters, MessageHandler
updater = Updater(token=KEY, use_context=True)
dispatcher = updater.dispatcher
def forwarder(update, context):
msg = update.channel_post
if msg:
print(msg)
forwardHandler = MessageHandler(Filters.text & (~Filters.command), forwarder)
dispatcher.add_handler(forwardHandler)
updater.start_polling()
updater.idle()
Bots can only get updates about channel posts if they are a member in that channel (and bots can only be added to channels as admin). If they are admins in the channel, they will receive updates just like from every other chat.
Requirements :
Your bot should be in the channel. obviously as an admin
so first just make a function :
def forwader(update , context):
context.bot.copy_message("#temporary2for" ,"#tempmain" , update.channel_post.message_id)
After that make handler :
forwadHandler= MessageHandler(Filters.text & (~Filters.command) , forwader)
Than register your handler :
dispatcher.add_handler(forwadHandler)
Than don't forget to start Bot polling :
updater.start_polling()
updater.idle()
Full code :
from telegram import bot
from telegram.ext import Updater , CommandHandler , Filters , MessageHandler
from config import useless
import logging
updater = Updater(token=useless, use_context=True)
dispatcher = updater.dispatcher
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
def forwader(update , context):
context.bot.copy_message("#temporary2for" ,"#tempmain" , update.channel_post.message_id)
forwadHandler= MessageHandler(Filters.text & (~Filters.command) , forwader)
dispatcher.add_handler(forwadHandler)
updater.start_polling()
updater.idle()
Some Import are useless .
how i can control if an userbot is in FloodWait or PeerFlood(is limited) without do an invite/chat request?
I send a message to SpamBot but it informs me only if the userbot is limited, no if is in FloodWait.
Thanks and sorry for my bad english!
Please see the Telethon docs for how to handle the various RPC errors gracefully.
Example for FloodWait From the docs:
from telethon import errors
try:
messages = await client.get_messages(chat)
print(messages[0].text)
except errors.FloodWaitError as e:
print('Have to sleep', e.seconds, 'seconds')
time.sleep(e.seconds)
How can I check if my userbot is restricted?
You can check only if your self is restricted, that means you can't check if a different user is restricted.
import asyncio
from telethon import TelegramClient
name = 'test'
api_id = '1043101'
api_hash = '5ade788056adad54e71aa558e38337bc'
client = TelegramClient(name, api_id, api_hash)
client.start(phone=+xxxxxxxxxx)
async def main():
if (await client_get_me()).restricted):
print('I'm restricted')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I want to add multiprocessing to my Flask-SocketIO server so I am trying to add a Redis message queue as per the Flask-SocketIO docs. Even without adding multiprocessing, the client is not receiving any events. Everything else is working fine (e.g. the web page is being served, HTTP requests are being made, database calls are being made). There are no error messages on the front or back end. Before I added the Redis queue it was working. I verified that the 'addname' SocketIO route is being hit and that the request.sid looks right. What am I doing wrong?
Very simplified server code:
external_sio = SocketIO(message_queue='redis://')
def requester(user, sid):
global external_sio
external_sio.emit('addname', {'data': 'hello'}, room=sid)
# do some stuff with requests and databases
external_sio.emit('addname', {'data': 'goodbye'}, room=sid)
def main():
app = Flask(__name__,
static_url_path='',
static_folder='dist',
template_folder='dist')
socketio = SocketIO(app)
#socketio.on('addname')
def add_name(user):
global external_sio
external_sio.emit('addname', {'data': 'test'}, room=request.sid)
requester(user.data, request.sid)
socketio.run(app, host='0.0.0.0', port=8000)
if __name__ == '__main__':
main()
Simplified client code (React Javascript):
const socket = SocketIOClient('ipaddress:8000')
socket.emit('addname', {data: 'somename'})
socket.on('addname', ({data}) => console.log(data))
The main server also needs to be connected to the message queue. In your main server do this:
socketio = SocketIO(app, message_queue='redis://')
In your external process do this:
external_sio = SocketIO(message_queue='redis://') # <--- no app on this one
After running the code, I try to enter a password (but I don’t have it) and can’t enter anything. I use VS Code
Please enter your phone (or bot token): 79622222693
Please enter the code you received: 40589
Please enter your password: (CANT ENTER ANYTHING, AND I DON'T HAVE ANY PASS ON MY ACCOUNT)
Tried different accounts.
from telethon import TelegramClient, sync
api_id = 973111111111145
api_hash = '05c6f86e67922222222222225ad7615a8'
client = TelegramClient('sessi1onname', api_id, api_hash)
client.start()
from telethon.sync import TelegramClient
api_id = 0
api_hash = ''
with TelegramClient('sessi1onname', api_id, api_hash) as client:
client.get_messages('me', "telethon sign in success")
use this code and then check your Saved Messages in telegram. will work for you. way you are trying is not sync!