Skip to content

Instantly share code, notes, and snippets.

@jeffehobbs
Created January 29, 2017 16:21
Show Gist options
  • Select an option

  • Save jeffehobbs/03f42868e45fba604b0b02ca0bf529e4 to your computer and use it in GitHub Desktop.

Select an option

Save jeffehobbs/03f42868e45fba604b0b02ca0bf529e4 to your computer and use it in GitHub Desktop.
trollbot.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# trollbot.py // Jeff Hobbs // Jan 2016
import os
import logging
import random
import configparser
import tweepy
#set path to logfile
PATH = os.path.dirname(os.path.abspath(__file__))
LOG_FILENAME = PATH + '/trollbot.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.CRITICAL)
# set up API keys from external config apikeys.txt file
config = configparser.ConfigParser()
config.read(PATH + '/apikeys.txt')
CONSUMER_KEY = config.get('apikey', 'consumer_key')
CONSUMER_SECRET = config.get('apikey', 'consumer_secret')
ACCESS_TOKEN = config.get('apikey', 'access_token')
ACCESS_TOKEN_SECRET = config.get('apikey', 'access_token_secret')
# authenticate with Twitter API
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
# choose output from file
def getOutput():
outputs = open(PATH + '/output.txt').read().splitlines()
output = random.choice(outputs)
output = output.replace('\n', '').replace('\r', '')
if (output[0] == "#" ):
getOutput()
else:
getRecipient(output)
# get recipient of output from file
def getRecipient(output):
recipients = open(PATH + '/input.txt').read().splitlines()
recipient = random.choice(recipients)
recipient = recipient.replace('\n', '').replace('\r', '')
if (recipient[0] == "#" ):
getRecipient(output)
else:
last_tweet = api.user_timeline(screen_name = recipient, count = 1)[0]
print "---"
print "TO: @" + str(recipient)
print "RE: http://twitter.com/" + str(recipient) + "/status/" + str(last_tweet.id)
print " \"" + str(last_tweet.text) + "\"\n"
tweetAt(recipient,output,last_tweet)
# send output as reply to recipient's latest tweet
def tweetAt(recipient,output,last_tweet):
# authenticate with Twitter
print " @" + recipient + " " + output
print "---\n"
try:
api.update_status("@" + recipient + " " + output, in_reply_to_status_id=str(last_tweet.id))
except tweepy.TweepError, e:
logging.critical(str(e))
# main function
if __name__ == '__main__':
getOutput()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment