Steps to create a Twitter bot with python

Date of writing: 2015.08.09

Thank you for always referring to your blog, Qita, Github, etc.

1. Preparation

  1. Access Twitter App
  2. Create a new app with [Create New App]
  3. Get various keys

2. Handle Twitter with Python

The environment is Python 3.5.1. There are many libraries that work with Twitter on Python. I've used the following three.

Mostly none

$ pip install twitter

I think you can usually install it like this.

Twitter bot

  1. Regular tweet type
  2. Real-time response type

I think there are two types of (though there may be others)

This time I would like to create these two types of bots.

1. Regular tweet type

import twitter

auth = twitter.OAuth(consumer_key="",
consumer_secret="",
token="",
token_secret="")

t = twitter.Twitter(auth=auth)

#Tweet only
status="Hello,World" #Tweet to post
t.statuses.update(status=status) #Post to Twitter

#Tweet with image
pic="" #If you post an image, the image path
with open(pic,"rb") as image_file:
 image_data=image_file.read()
pic_upload = twitter.Twitter(domain='upload.twitter.com',auth=auth)
id_img1 = pic_upload.media.upload(media=image_data)["media_id_string"]
t.statuses.update(status=status,media_ids=",".join([id=img1]))

If it is a bot that regularly tweets images and words, it is ok if you modify this a little!

There are several ways to run a script regularly, but using crontab is the best (I personally hate the notation).

Crontab is a tool that executes commands regularly when the set time is reached. -How to write crontab

2. Real-time response type

Use Streaming API.

import twitter

auth = twitter.OAuth(consumer_key="",
consumer_secret="",
token="",
token=secret="")

t = twitter.Twitter(auth=auth)
#Use Userstream
t_userstream = twitter.TwitterStream(auth=auth,domain='userstream.twitter.com')

#Your timeline tweets and user information flow
for msg in twitter.userstream.user():
 print(msg)

In the program, in the contents of msg Various information such as user information and tweet information will flow one by one, so please process it so that you can get the information you want.

I will post only the ones I use often.

parameter contents
in_reply_to_screen_name Reply destination user name
text Tweet content
name The name of the user who tweeted(≠screen_name)
media_url The URL of the media attached to the tweet

I wonder if I haven't used the others so far ..

For example, if you want to create a bot that will reply when a reply comes

.
.
for msg in twitter.userstream.user():
 #Reply to TL TWITTER_Branch if ID is included
 if msg['in_reply_to_screen_name']=="TWITTER_ID":
  tweet = "@"+msg['user']['screen_name']+" "+"Reply Thanks you"
  t.statuses.update(status=tweet)
  

It can be created like this (example)

For those who want to know in detail what kind of information can be obtained from the flowing information (msg) [Data structure when acquired by Twitter API](http://biokids.org/?%A4%C9%A4%D6%A4%AA%2FTwitter%A4%C7%CD%B7%A4%DC%A4% Please see A6% A1% AA% 2F% A5% C7% A1% BC% A5% BF% B9% BD% C2% A4).

I will write about tweepy at a later date.

Actually, there may be a more efficient operation method, but for now it looks like this.


update_name Feeling like playing with twitter profile settings on CUI

import tweepy

auth = OAuthHandler(consumer_key="",consumer_secret="")
auth.set_access_token(token="",token=secret="")
api = API(auth)
api.update_profile(name='New name')

For other update_profiles, see POST account / update_profile | Twitter Developers.

For me personally, tweepy is easier to see and use than python-twitter. API Reference — tweepy 3.5.0 documentation So if you think you can do this, go to the twitter official and the reference of each library !!

Site that I was allowed to refer to

-Kivantium activity diary Using Twitter with Python ~ Introduction of Tweepy ~

Recommended Posts

Steps to create a Twitter bot with python
Create a Mastodon bot with a function to automatically reply with Python
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Let's make a Twitter Bot with Python!
Make a Twitter trend bot with heroku + Python
Create a LINE BOT with Minette for Python
Create a directory with python
I wrote a script to create a Twitter Bot development environment quickly with AWS Lambda + Python 2.7
Steps to create a Python virtual environment with VS Code on Windows
I made a Twitter BOT with GAE (python) (with a reference)
[Python] How to create a 2D histogram with Matplotlib
Steps to create a Django project
Create a virtual environment with Python!
5 Ways to Create a Python Chatbot
Easily post to twitter with Python 3
Create a list in Python with all followers on twitter
Probably the easiest way to create a pdf with Python3
Create a message corresponding to localization with python translation string
Create a bot to retweet coronavirus information
Create a dummy image with Python + PIL.
[Python] [LINE Bot] Create a parrot return LINE Bot
Create a word frequency counter with Python 3.4
Create a bot that boosts Twitter trends
Try to create a python environment with Visual Studio Code & WSL
I tried to create a list of prime numbers with python
How to create a heatmap with an arbitrary domain in Python
[LINE Messaging API] Create a BOT that connects with someone with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
Create a frame with transparent background with tkinter [Python]
[Python] List Comprehension Various ways to create a list
Edit Excel from Python to create a PivotTable
[Cloudian # 3] Try to create a new object storage bucket with Python (boto3)
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 1)
Create a Twitter BOT service with GAE / P + Tweepy + RIOT API! (Part 2)
Python beginners decided to make a LINE bot with Flask (Flask rough commentary)
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
I want to create a window in Python
How to create a JSON file in Python
Try to draw a life curve with python
I made a Twitter fujoshi blocker with Python ①
I want to make a game with Python
Create a tool to automatically furigana with html using Mecab from Python3
Create a virtual environment with conda in Python
Create a page that loads infinitely with python
[Note] Create a one-line timezone class with python
You can easily create a GUI with Python
Try to make a "cryptanalysis" cipher with Python
Post youtube soaring title to twitter with python3
Create a color bar with Python + Qt (PySide)
Steps to develop a web application in Python
Decide to assign a laboratory with Python (fiction)
Create a decision tree from 0 with Python (1. Overview)
Create a new page in confluence with Python
Create a color-specified widget with Python + Qt (PySide)
Try to make a dihedral group with Python
How to create a multi-platform app with kivy
Create a Photoshop format file (.psd) with python
[Outlook] I tried to automatically create a daily report email with Python
Create a Python environment
Create a Python console application easily with Click
I want to write to a file with Python