• Guest
HabraHabr
  • Main
  • Users

  • Development
    • Programming
    • Information Security
    • Website development
    • JavaScript
    • Game development
    • Open source
    • Developed for Android
    • Machine learning
    • Abnormal programming
    • Java
    • Python
    • Development of mobile applications
    • Analysis and design of systems
    • .NET
    • Mathematics
    • Algorithms
    • C#
    • System Programming
    • C++
    • C
    • Go
    • PHP
    • Reverse engineering
    • Assembler
    • Development under Linux
    • Big Data
    • Rust
    • Cryptography
    • Entertaining problems
    • Testing of IT systems
    • Testing Web Services
    • HTML
    • Programming microcontrollers
    • API
    • High performance
    • Developed for iOS
    • CSS
    • Industrial Programming
    • Development under Windows
    • Image processing
    • Compilers
    • FPGA
    • Professional literature
    • OpenStreetMap
    • Google Chrome
    • Data Mining
    • PostgreSQL
    • Development of robotics
    • Visualization of data
    • Angular
    • ReactJS
    • Search technologies
    • Debugging
    • Test mobile applications
    • Browsers
    • Designing and refactoring
    • IT Standards
    • Solidity
    • Node.JS
    • Git
    • LaTeX
    • SQL
    • Haskell
    • Unreal Engine
    • Unity3D
    • Development for the Internet of things
    • Functional Programming
    • Amazon Web Services
    • Google Cloud Platform
    • Development under AR and VR
    • Assembly systems
    • Version control systems
    • Kotlin
    • R
    • CAD/CAM
    • Customer Optimization
    • Development of communication systems
    • Microsoft Azure
    • Perfect code
    • Atlassian
    • Visual Studio
    • NoSQL
    • Yii
    • Mono и Moonlight
    • Parallel Programming
    • Asterisk
    • Yandex API
    • WordPress
    • Sports programming
    • Lua
    • Microsoft SQL Server
    • Payment systems
    • TypeScript
    • Scala
    • Google API
    • Development of data transmission systems
    • XML
    • Regular expressions
    • Development under Tizen
    • Swift
    • MySQL
    • Geoinformation services
    • Global Positioning Systems
    • Qt
    • Dart
    • Django
    • Development for Office 365
    • Erlang/OTP
    • GPGPU
    • Eclipse
    • Maps API
    • Testing games
    • Browser Extensions
    • 1C-Bitrix
    • Development under e-commerce
    • Xamarin
    • Xcode
    • Development under Windows Phone
    • Semantics
    • CMS
    • VueJS
    • GitHub
    • Open data
    • Sphinx
    • Ruby on Rails
    • Ruby
    • Symfony
    • Drupal
    • Messaging Systems
    • CTF
    • SaaS / S+S
    • SharePoint
    • jQuery
    • Puppet
    • Firefox
    • Elm
    • MODX
    • Billing systems
    • Graphical shells
    • Kodobred
    • MongoDB
    • SCADA
    • Hadoop
    • Gradle
    • Clojure
    • F#
    • CoffeeScript
    • Matlab
    • Phalcon
    • Development under Sailfish OS
    • Magento
    • Elixir/Phoenix
    • Microsoft Edge
    • Layout of letters
    • Development for OS X
    • Forth
    • Smalltalk
    • Julia
    • Laravel
    • WebGL
    • Meteor.JS
    • Firebird/Interbase
    • SQLite
    • D
    • Mesh-networks
    • I2P
    • Derby.js
    • Emacs
    • Development under Bada
    • Mercurial
    • UML Design
    • Objective C
    • Fortran
    • Cocoa
    • Cobol
    • Apache Flex
    • Action Script
    • Joomla
    • IIS
    • Twitter API
    • Vkontakte API
    • Facebook API
    • Microsoft Access
    • PDF
    • Prolog
    • GTK+
    • LabVIEW
    • Brainfuck
    • Cubrid
    • Canvas
    • Doctrine ORM
    • Google App Engine
    • Twisted
    • XSLT
    • TDD
    • Small Basic
    • Kohana
    • Development for Java ME
    • LiveStreet
    • MooTools
    • Adobe Flash
    • GreaseMonkey
    • INFOLUST
    • Groovy & Grails
    • Lisp
    • Delphi
    • Zend Framework
    • ExtJS / Sencha Library
    • Internet Explorer
    • CodeIgniter
    • Silverlight
    • Google Web Toolkit
    • CakePHP
    • Safari
    • Opera
    • Microformats
    • Ajax
    • VIM
  • Administration
    • System administration
    • IT Infrastructure
    • *nix
    • Network technologies
    • DevOps
    • Server Administration
    • Cloud computing
    • Configuring Linux
    • Wireless technologies
    • Virtualization
    • Hosting
    • Data storage
    • Decentralized networks
    • Database Administration
    • Data Warehousing
    • Communication standards
    • PowerShell
    • Backup
    • Cisco
    • Nginx
    • Antivirus protection
    • DNS
    • Server Optimization
    • Data recovery
    • Apache
    • Spam and antispam
    • Data Compression
    • SAN
    • IPv6
    • Fidonet
    • IPTV
    • Shells
    • Administering domain names
  • Design
    • Interfaces
    • Web design
    • Working with sound
    • Usability
    • Graphic design
    • Design Games
    • Mobile App Design
    • Working with 3D-graphics
    • Typography
    • Working with video
    • Work with vector graphics
    • Accessibility
    • Prototyping
    • CGI (graphics)
    • Computer Animation
    • Working with icons
  • Control
    • Careers in the IT industry
    • Project management
    • Development Management
    • Personnel Management
    • Product Management
    • Start-up development
    • Managing the community
    • Service Desk
    • GTD
    • IT Terminology
    • Agile
    • Business Models
    • Legislation and IT-business
    • Sales management
    • CRM-systems
    • Product localization
    • ECM / EDS
    • Freelance
    • Venture investments
    • ERP-systems
    • Help Desk Software
    • Media management
    • Patenting
    • E-commerce management
    • Creative Commons
  • Marketing
    • Conferences
    • Promotion of games
    • Internet Marketing
    • Search Engine Optimization
    • Web Analytics
    • Monetize Web services
    • Content marketing
    • Monetization of IT systems
    • Monetize mobile apps
    • Mobile App Analytics
    • Growth Hacking
    • Branding
    • Monetize Games
    • Display ads
    • Contextual advertising
    • Increase Conversion Rate
  • Sundry
    • Reading room
    • Educational process in IT
    • Research and forecasts in IT
    • Finance in IT
    • Hakatonas
    • IT emigration
    • Education abroad
    • Lumber room
    • I'm on my way

Overhear telegram chat with your customer

Somehow I wanted to, the messages of one of the telegraph chat rooms were stored on my disk (without starting a regular client). I will not reveal their motives, but the possibility of this seemed necessary and useful.
 3r33450.
To this end, in a telegram has the bots. Habré has several articles dealing with bots, for example: ". Chat Assistant to the site ".
 3r33450.
The bot allows you to read and send messages, you do not need a phone to register a bot and there can be any number of bots. But the bot name includes the word "bot", which can cause a host chat unnecessary questions.
 3r33450.
But as they say, right question - half of the answer.
https://telegram.org/apps#source-code
 3r33450.
However, the easiest to use was the python library: Pure Python 3 MTProto API Telegram client library called
"telethon"
 3r33450.
Only here is the problem. I do not know python. Well, there is a reason to meet.
 
According to a manual on telethon, his installation is very simple. Enough to run the command line:
 
pip3 install telethon
 
Pitfalls, met me at installation:
 
 
PIP3 is not installed (installer for Python).
 
 
sudo apt-get -y install python3-pip
 
 
3r376. The library works only on python version> 3.5. So, you may have to update it.
 3r33450.
 
Everything is established. Flipping readme.txt on.
 
The next item is the creation of a telegraph client How, already? Well, it's simple. However, you must first zaregistritrovat itself as the creator of the client.
 3r33450.
Go to the website telegram: https://my.telegram.org
 3r33450. We introduce the phone and wait for the confirmation code in the native client telegram. He is quite long (12 characters) and inconvenient to enter.
 
Go to the item " API ". We look for the "Telegram API" and go to the "Creating an application" ( [url]Https://my.telegram.org/apps[/url] ).
 
Fill field
App title
and
Short name
, Press
«Create application»
and remember two variables:
api_id
and 3r3138. api_hash
.
 
It's time to make the customer.
 3r33450.
from telethon import TelegramClient, sync
3r33450. # Insert api_id and api_hash
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
3r33450. client = TelegramClient ('session_name', api_id, api_hash)
client.start ()

 3r33450.

session_name - you can insert any name. You will be asked to enter the phone number and send a confirmation code. The client will work without a telephone request (as long as not to change session_name). The file will appear next to your program. session_name.session


 

If there are no errors, the client is ready. Only here, no output. Let's try to get some useful inforfmatsiyu.


 3r33450.

We learn a little about yourself:


 
    print (client.get_me (). stringify ())    

 

the result is given as:


 
  
User (
photo = None,
last_name = 'Pupkin',
first_name = 'Vasya',
id = 12345678?
phone = '79041234567',
- Something else.
)

 

We can send a message from yourself:


 
    client.send_message ( 'username', 'Hello! Talking to you from Telethon')    

 3r33450.

You can and picture 3r3444.
 

    client.send_file ( 'username', '/home/myself/Pictures/holidays.jpg')    

 3r33450.

How do others:


 
    client.download_profile_photo ( 'me')    

 

We look at what we signed chats:


 
    print all chats name
for dialog in client.iter_dialogs ():
print (dialog.title)

 3r33450.

read all chat messages "chat_name" (carefully, there can be a lot of messages)


 
    messages = client.get_entity ( 'chat_name')
print (messages)

 3r33450.

view all users

chat.
 
    participants = client.get_participants ( 'chat_name')
print (participants)

 

Indulged?
 3r33450. Now, in fact, we are doing something for which we all started this


 

We need a program that is watching the new messages in a specific channel.


 3r33450.

That the client did not finish work, after client.start () we interpose a line:


 3r33450.
    client.run_until_disconnected (  ).  

 3r33450.

This construct (inserted before client.start ()) displays only new messages:


 3r33450.
    @ Client.on (events.NewMessage (chats = ( 'chat_name')))
async def normal_handler (event):
# Print (event.message)
print (event.message.to_dict ()['message'])

 

Let's face it.


 3r33450.
    @ Client.on (events.NewMessage (chats = ( 'chat_name')))    

 3r33450.

Creates an event that fires when a new message appears


 3r33450.
    print (event.message)    

 3r33450.

displays a message like this:


 3r33450.
    Message (edit_date = None, views = None, reply_markup = None, fwd_from = None, id = 18? entities =[], Post = False, mentioned = False, via_bot_id = None, media_unread = False, out = True, media = None , date = datetime.datetime (201? 1? ? ? 2? 2? tzinfo = datetime.timezone.utc), to_id = PeerChannel (channel_id = 123456789), reply_to_msg_id = None, from_id = 12345678? silent = False, grouped_id = None, post_author = None, message = 'hello telegram')    

 

From all this we need a field: "message = 'hello telegram'":


 3r33450.
    print (event.message.to_dict ()['message'])    

 3r33450.

The message received, but from whom it is not clear, because in a message only a user ID. To match the user ID and the name, download all IM users and put them in a dictionary (hash) as d[id]= "first_name last_name"


 
    participants = client.get_participants (group)
users = {}
3r33450. for partic in client.iter_participants (group):
lastname = ""
if partic.last_name:
lastname = partic.last_name
users[partic.id]= partic.first_name + "" + lastname

 

Now we can find out who sent the message:


 3r33450.
    s_user_id = event.message.to_dict ()['from_id']
user_id = int (s_user_id)
user = d.get (user_id)

 3r33450.

In principle, you can get the user name from the telegram directly, but if people are a little bit easier with the dictionary.


 

Pull out from a message sent date:


 3r33450.
    mess_date = event.message.to_dict (['date']). 3r33434.  

 3r33450.

All, all of the data we have. It remains to be written to a file.
 3r33450. To do this, first open the file for writing:


 
    f = open ('messages_from_chat', 'a')    

 

And write the message:


 
    f.write (mess_date.strftime ( "% d-% m-% Y% H:% M") + "n")
f.write (user + "n")
f.write (user_mess + "nn")
f.flush (
).

 3r33450.

That's all! All that I needed, the program does. Utility, of course, buggy, but its task is performed.


 

Python was not so difficult 3r33384. as he is painted , Especially description and the different libraries on the Internet is full. Write a couple more utilitok and getting used to it, you can use it as a scripting language instead of bash.


 3r33450. 3r33333. 3r33333. All of the text utility: [/b]
    from telethon import TelegramClient, sync, events
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
3r33450. client = TelegramClient ('session_name', api_id, api_hash)
3r33450. @ client.on (events.NewMessage (chats = ('chat_name')))
async def normal_handler (event):
# Print (event.message)
user_mess = event.message.to_dict (['message']). 3r33450. 3r33450. s_user_id = event.message.to_dict ()['from_id']3r33450. user_id = int (s_user_id)
user = d.get (user_id)
3r33450. mess_date = event.message.to_dict (['date']). 3r33450.
f.write (mess_date.strftime ( "% d-% m-% Y% H:% M") + "n")
f.write (user + "n")
f.write (user_mess + "nn")
3r33450. f.flush ()
3r33450. client.start ()
group = 'group_name'
participants = client.get_participants (group)
users = {}
for partic in client.iter_participants (group):
lastname = ""
if partic.last_name:
lastname = partic.last_name
users[partic.id]= Partic.first_name + "" + lastname
f = open ('messages_from_chat', 'a')
3r33450. client.run_until_disconnected ()
f.close (
).
 
Full description of the library. .
3r33450.

It may be interesting

  • Comments
  • About article
  • Similar news
This publication has no comments.

weber

Author

3-10-2018, 00:11

Publication Date

Development / Programming

Category
  • Comments: 0
  • Views: 411
Repost from a third-party Telegram
Mitap Sbertech in Rostov-on-Don
Application for the framework for the
Telegram API daemon - glue the serial
Why do we love Telegram?
A small library for the application of
Write a comment
Name:*
E-Mail:


Comments
The GW1NRF Bluetooth FPGA is the first uSoC FPGA to offer a built in Bluetooth transceiver to wirelessly communicate data with 32-Bit Microprocessor. Check Out: Gowin Semiconductor


Miro Paris vous propose une large gamme d'accessoire de beauté, maquillage, skincare, kbeauty, crèmes en provenance de Corée du sud, Japon, et Hong Kong. Check Out: Cosmétiques Asiatiques
Yesterday, 21:22

noorseo

LIMITED EDITION Experience Virtual Reality Now! Version 2.0 Discount40% OFF See More15% OFFFASHION & ACCESSORIESApparel Fashion Price starting from$5.99 See More20% OFFLIVEBYCARE Combo 5x Pillows Color Discount20% OFF Shop Now Bluetooth Latest Speakers Price starting from$22.99 XBOX CONTROLLER WHITE COLOR Discount 10% SMART APPLE PRODUCTS 15% OFF12% LISTEN TO REAL MUSIC WITH BEATSHealth & Fitness

Yesterday, 17:42

raymond weber

PERFECT size dumpster rentals for your residential needs, they are the ideal fit for your driveway. EASY simple pricing so you have everything upfront. FAST dumpster delivery. Check out: Austin Dumpster Rental
Yesterday, 17:03

saifwordpress

This article was written by a real thinking writer. I agree many of the with the solid points made by the writer. I'll be back. official 123movies websites
Yesterday, 17:00

Legend SEO

LIMITED EDITION Experience Virtual Reality Now! Version 2.0 Discount40% OFF See More15% OFFFASHION & ACCESSORIESApparel Fashion Price starting from $ 5.99 See More20% OFFLIVEBYCARE Combo 5x Pillows Color Discount20% OFF Shop Now Bluetooth Latest Speakers Price starting from $ 22.99 XBOX CONTROLLER WHITE COLOR Discount 10% SMART APPLE PRODUCTS 15% OFF12% LISTEN TO REAL MUSIC WITH BEATS [url = https: //topofferscart.online/] Health & Fitness [/ url]

Yesterday, 15:57

nushra45

Adv
Website for web developers. New scripts, best ideas, programming tips. How to write a script for you here, we have a lot of information about various programming languages. You are a webmaster or a beginner programmer, it does not matter, useful articles will help to make your favorite business faster.

Login

Registration Forgot password