Program That Reads Telegram Message and Enter It Into Metatrader
In this tutorial, we are going to use the CSV file that we generated in Scraping Telegram Members tutorial to transport bulk messages to our scraped Telegram group members using Telegram API and Python Telethon library. And so if you did not already checked that, visit this tutorial and acquire how to become this file. Basically we volition feed our new Python script with that CSV file to read usernames or user IDs from it and send a message to them.
Get Telegram API Fundamental
As stated in the previous tutorial you need to get your Telegram API credentials to be able to use the API. So don't hesitate and bank check the previous tutorial and use the guide to get your own Telegram API credentials, or simply follow these steps:
• Sign upwards for Telegram using whatever awarding.
• Log in to your Telegram cadre: https://my.telegram.org.
• Go to 'API development tools' and fill out the form.
• You will become basic addresses as well as the api_id and api_hash parameters required for user authorization.
Install Telethon
Also yous need to install Telethon using pip .
python - thousand pip install telethon |
Note: If you are on Linux or Mac, you might need to use sudo before pip to avoid permissions issues.
Allow'southward go started.
Create Client Object and Login
Whenever y'all want to use Telethon, starting time step should be logging into the API. So you have to create a client object and check if information technology'south already authorized otherwise inquire for an OTP countersign.
So create your customer object beginning.
from telethon . sync import TelegramClient api_id = 123456 api_hash = 'YOUR_API_HASH' telephone = '+111111111111' client = TelegramClient ( phone , api_id , api_hash ) |
Connect and check if the customer is authorized. Otherwise prompt the user to enter the code they received from Telegram.
client . connect ( ) if not client . is_user_authorized ( ) : customer . send_code_request ( phone ) client . sign_in ( phone , input ( 'Enter the code: ' ) ) |
Read Members from CSV File
We are passing the file proper name in the sys . argv parameters. sys . argv is a listing in Python, which contains the control-line arguments passed to the script.
So if you run python sendMessage . py users . csv in the command line sys . argv will render a list like this:
[ 'sendMessage.py' , 'users.csv' ] |
Every bit you can see, the first item in the list is the name of the script and the 2d item is the proper noun of our CSV file. So we can access the file name with sys . argv [ i ] .
Now y'all have the proper noun (or path) of our CSV file and y'all tin can employ Python's csv module to read the file and create a list of users.
Import the required modules
Create a dictionary for every user and append that to our user listing.
input_file = sys . argv [ one ] users = [ ] with open up ( input_file , encoding = 'UTF-eight' ) every bit f : rows = csv . reader ( f , delimiter = "," , lineterminator = "\n" ) next ( rows , None ) for row in rows : user = { } user [ 'username' ] = row [ 0 ] user [ 'id' ] = int ( row [ 1 ] ) user [ 'access_hash' ] = int ( row [ 2 ] ) user [ 'name' ] = row [ 3 ] users . append ( user ) |
Note: You need to cast the user id and access hash to integer blazon.
Note: We skip the first row in the CSV file (header) using the next function.
Prompt to Send by User ID or Username
Equally I mentioned in the previous tutorial, not all telegram members have a username. Also, access hash for every user is different for every Telegram business relationship. It ways that if you scrape users with a Telegram business relationship and you want to transport messages with another account and then you cannot use those access hashes to become the users. Simply y'all tin utilise usernames. To solve this problem and avert errors we will ask your Python script user whether he/she wants to use Telegram username or user ID to send the messages.
mode = int ( input ( "Enter i to send past user ID or 2 to transport by username: " ) ) |
Ship Messages
Now, you have all the requirements to start sending messages.
Create a list of messages and randomly select one of them to send to a user. As well, format the bulletin to include the proper name of the user.
letters = [ "Hello {}, How are y'all?" , "Hi {}, What'due south upward?" , "Hey {}, practise you want to gotrained?" ] |
Now, loop through every user and send a message. Consider that if you lot send letters too quickly y'all will get a PeerFloodError from Telegram. And then we will handle this fault using a try, except cake and exit the plan if information technology happened. Otherwise the account might get banned from Telegram because of spamming. Likewise, add a sleep fourth dimension between each message to avoid inundation error.
Nosotros are going to do it footstep past step.
Loop through every user and get the receiver entity depending on the "fashion" entered earlier.
from telethon . tl . types import InputPeerUser for user in users : if mode == 2 : if user [ 'username' ] == "" : continue receiver = client . get_input_entity ( user [ 'username' ] ) elif mode == 1 : receiver = InputPeerUser ( user [ 'id' ] , user [ 'access_hash' ] ) else : print ( "Invalid Mode. Exiting." ) sys . leave ( ) |
Select a bulletin from message list randomly.
import random bulletin = random . choice ( messages ) |
Format the message with user'due south proper noun and ship it.
client . send_message ( receiver , message . format ( user [ 'proper name' ] ) |
The complete code block for sending messages including exception handling will await like this:
one ii three 4 5 half dozen 7 8 nine 10 11 12 13 14 fifteen sixteen 17 18 xix twenty 21 22 23 24 25 26 27 28 29 30 | from telethon . tl . types import InputPeerUser from telethon . errors . rpcerrorlist import PeerFloodError import random SLEEP_TIME = thirty for user in users : if mode == 2 : if user [ 'username' ] == "" : continue receiver = client . get_input_entity ( user [ 'username' ] ) elif mode == i : receiver = InputPeerUser ( user [ 'id' ] , user [ 'access_hash' ] ) else : print ( "Invalid Style. Exiting." ) client . disconnect ( ) sys . exit ( ) message = random . choice ( messages ) effort : impress ( "Sending Bulletin to:" , user [ 'proper noun' ] ) customer . send_message ( receiver , message . format ( user [ 'proper name' ] ) ) print ( "Waiting {} seconds" . format ( SLEEP_TIME ) ) time . sleep ( SLEEP_TIME ) except PeerFloodError : print ( "Getting Flood Error from telegram. Script is stopping now. Delight endeavour again afterwards some time." ) client . disconnect ( ) sys . exit ( ) except Exception as e : print ( "Mistake:" , e ) print ( "Trying to go on..." ) continue |
Project Source Lawmaking for Messaging Telegram Members Tutorial
Here is the completed code for this tutorial.
1 2 iii 4 v 6 7 viii 9 x 11 12 13 14 15 sixteen 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | from telethon . sync import TelegramClient from telethon . tl . types import InputPeerUser from telethon . errors . rpcerrorlist import PeerFloodError import sys import csv import random import time api_id = 123456 api_hash = 'YOUR_API_HASH' telephone = '+111111111111' SLEEP_TIME = 30 client = TelegramClient ( phone , api_id , api_hash ) client . connect ( ) if not client . is_user_authorized ( ) : customer . send_code_request ( phone ) client . sign_in ( telephone , input ( 'Enter the code: ' ) ) input_file = sys . argv [ i ] users = [ ] with open up ( input_file , encoding = 'UTF-viii' ) equally f : rows = csv . reader ( f , delimiter = "," , lineterminator = "\n" ) next ( rows , None ) for row in rows : user = { } user [ 'username' ] = row [ 0 ] user [ 'id' ] = int ( row [ 1 ] ) user [ 'access_hash' ] = int ( row [ ii ] ) user [ 'proper name' ] = row [ iii ] users . append ( user ) style = int ( input ( "Enter 1 to send past user ID or two to send past username: " ) ) messages = [ "How-do-you-do {}, How are you?" , "Hello {}, What's up?" , "Hey {}, do you want to gotrained?" ] for user in users : if manner == 2 : if user [ 'username' ] == "" : proceed receiver = client . get_input_entity ( user [ 'username' ] ) elif mode == 1 : receiver = InputPeerUser ( user [ 'id' ] , user [ 'access_hash' ] ) else : print ( "Invalid Manner. Exiting." ) customer . disconnect ( ) sys . exit ( ) message = random . pick ( messages ) attempt : print ( "Sending Message to:" , user [ 'proper name' ] ) client . send_message ( receiver , message . format ( user [ 'name' ] ) ) print ( "Waiting {} seconds" . format ( SLEEP_TIME ) ) time . sleep ( SLEEP_TIME ) except PeerFloodError : impress ( "Getting Flood Error from telegram. Script is stopping now. Please endeavour again after some time." ) client . disconnect ( ) sys . exit ( ) except Exception as eastward : print ( "Fault:" , e ) print ( "Trying to continue..." ) continue client . disconnect ( ) print ( "Done. Bulletin sent to all users." ) |
I speak Python!
Majid Alizadeh is a freelance developer specialized in web development, web scraping and automation. He provides high quality and sophisticated software for his clients. Abreast Python he works with other languages like Ruby, PHP and JS as well.
Source: https://python.gotrained.com/messaging-telegram-members-telethon/
0 Response to "Program That Reads Telegram Message and Enter It Into Metatrader"
إرسال تعليق