📜 ⬆️ ⬇️

Simple Twitter bot in Python

In this article, I would like to share the experience of writing a small twitter bot in Python.

Introduction



I’ve been bothered by a well-known “pichalka-bot” on Twitter that automatically sends replai to everyone who mentions the word “pichalka” in his tweet. Since at that moment I was actively studying Python, it was decided to write on it.
')

Training



As a library for working with the Twitter API, I took tweepy . This is a fairly simple and convenient library; besides, there are some code samples and good documentation in its repository in Google Code. It is also in the Ubuntu and Debian repositories, so you can easily install it with sudo apt-get install python-tweepy .

Development



1. For the bot to work, you must register a new application on Twitter. Follow the link and fill in all the fields.

image

After that you will receive 2 keys for OAuth authorization.

image

You also need to change the rights of the application. Tab “Settings”, Access -> Read and Write

image

2. Now you need to get another 2 keys, individual for each user. To do this, you can click the “Create access token” button on the application page, or use a small sample code from the tweepy documentation.

image

Option with sample code:

 import tweepy, webbrowser CONSUMER_KEY = 'paste your Consumer Key here' CONSUMER_SECRET = 'paste your Consumer Secret here' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth_url = auth.get_authorization_url() webbrowser.open(auth_url) verifier = raw_input('PIN: ').strip() auth.get_access_token(verifier) print "ACCESS_KEY = '%s'" % auth.access_token.key print "ACCESS_SECRET = '%s'" % auth.access_token.secret 


Save it to a file, insert the keys received during the registration of the application, and run it. Go to the proposed address, and Twitter will give you a pin code that you will need to enter into the console. Upon successful authorization, you will receive those two user keys.



3. Now you can go to the code of the bot itself:

 #coding: utf-8 import oauth, tweepy, sys, locale, threading from time import localtime, strftime, sleep replyed=[''] search_reply_words={'':'  ,    "",  .','':'  ,    "",  .'} update_time=60 #  def Tweet(twit,id_reply): if len(twit)<=140 and len(twit)>0: api.update_status(twit,id_reply) #  ( ) return True else: return False def init(): # global api #consumer_key = "" #consumer_secret = "" #access_key="" #access_secret="" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api=tweepy.API(auth) class TwiBot(threading.Thread): def __init__ (self, keyword,answer): self.keyword = keyword self.answer=answer threading.Thread.__init__(self) def run (self): global replyed,api request=api.search(self.keyword) #     for i in request: if i.from_user!='thevar1able' and i.id not in replyed: #           ... try: Tweet('@'+i.from_user+self.answer,i.id) #... print strftime('[%d/%m %H:%M:%S]',localtime())+' Reply to @'+i.from_user+'('+str(i.from_user_id)+')' except: print strftime('DUP [%d/%m %H:%M:%S]',localtime())+' Reply to @'+i.from_user+'('+str(i.from_user_id)+')' replyed.append(i.id) return True init() #  while not False: #  for word in search_reply_words: TwiBot(word, search_reply_words[word]).start() #       print strftime('[%d/%m %H:%M:%S]',localtime())+' Updating for word "'+str(word)+'"...' sleep(1) sleep(update_time) 


To work correctly, you need to insert the obtained keys into variables in the code: the keys from the application page are consumer_key and consumer_secret, the user keys are access_key and access_secret. You also need to correct the keywords to search for tweets and the answers to them in the variable search_reply_words.

That's all for today.

Thanks for attention! I hope it was interesting and useful.

Source: https://habr.com/ru/post/127237/


All Articles