Skip to content

Instantly share code, notes, and snippets.

@saralgyaan saralgyaan/bot.py
Created Apr 5, 2019

Embed
What would you like to do?
It is Twitter Bot.
"""bot.py
It is Twitter Bot.
If someone(X) send an Image(with one or more person in it) to you Twitter Handle, it will automatically remove the background of the image and sent 'X' a tweet containing the image without the background.
Requires
--------
Tweepy
------
installation : pip install tweepy
Pillow
------
installation : pip install Pillow
Python Decouple
---------------
installation : pip install python-decouple
Twitter Account and API credentials
-----------------------------------
setup: Login to developer.twitter.com, create an app and generate Consumer Key, Consumer Secret, Access Token and Access Secret
remove.bg account and api
-------------------------
setup: Login to https://remove.bg and create an account and create a free API key. Free API provides 50 calls per month.
Usage
-----
Create .env file in the same directory and copy paste all the credentials of twitter and remove.bg API. Run the script python bot.py. Tweet at the handle with a pic.
"""
import tweepy
import requests
from decouple import config
from io import BytesIO
from PIL import Image
# authentication
auth = tweepy.OAuthHandler(config("CONSUMER_KEY"), config("CONSUMER_SECRET"))
auth.set_access_token(config("ACCESS_TOKEN"), config("ACCESS_SECRET"))
# API instance
api = tweepy.API(auth)
def remove_bg(filename):
"""Returns the image without the background
Requires
--------
remove.bg api key : save it in .env file as BG_API_KEY
request module
Parameters
----------
filename : str (default is 'temp.png')
Filename of the un-edited image downloaded by tweet_image() method with default name 'temp.png'
Returns
-------
no-bg.png : png
Image without the background.
"""
response = requests.post(
'https://api.remove.bg/v1.0/removebg',
files={'image_file': open(filename, 'rb')},
data={'size': 'auto'},
headers={'X-Api-Key': config('BG_API_KEY')},)
if response.status_code == requests.codes.ok:
with open('no-bg.png', 'wb') as out:
out.write(response.content)
else:
print("Error:", response.status_code, response.text)
def tweet_image(url, username, status_id):
"""Pick up the tweet with an image from Twitter Stream, downloads the image and saves it as temp.png, pass that image to remove_bg() method and then tweet the image without background ('no-bg.png') to the user
Parameters
----------
url : url
url of the tweet stream.
username: str
auto-populated by on_status method of MyStreamListener class.
status_id :
auto-populated by on_status method of MyStreamListener class.
Sends
-----
A tweet in reply to the original tweet containing the image without the background
"""
filename = 'temp.png'
response = requests.get(url, stream=True)
if response.status_code == 200:
i = Image.open(BytesIO(request.content))
i.save(filename)
remove_bg(filename)
api.update_with_media('no-bg.png', status=f'@{username}, Here is the picture without the background', in_reply_to_status_id=status_id)
else:
print("unable to download image")
class MyStreamListener(tweepy.StreamListener):
"""
A Stream listener which inherits tweepy.StreamListener
It looks for a tweet matching the filter (i.e. tweet mentioning @saralgyaan) then fetches the username and status_id of the tweet, checks if the tweet has an image and runs tweet_image() method
Attributes
----------
status:
Twitter status matching the filter.
Methods
-------
on_status
Runs tweet_image() method on meeting the conditions
"""
def on_status(self, status):
"""
It looks for a tweet matching the filter (i.e. tweet mentioning @saralgyaan) then fetches the username and status_id of the tweet, checks if the tweet has an image and runs tweet_image() method
Attributes
----------
status:
Twitter status matching the filter.
Runs
----
tweet_image() method
"""
username = status.user.screen_name
status_id = status.id
if 'media' in status.entities:
for image in status.entities['media']:
tweet_image(image['media_url'], username, status_id)
my_stream_listener = MyStreamListener()
stream = tweepy.Stream(auth, my_stream_listener)
stream.filter(track=['@saral_gyaan']) #looks for tweet with @saralgyaan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.