Skip to content

Instantly share code, notes, and snippets.

@Yuiki

Yuiki/tweetbot.py

Last active Dec 21, 2016
Embed
What would you like to do?
Twitter botサンプル
# -*- coding: utf-8 -*-
import tweepy
import ConfigParser
import random
import locale
import datetime
import pytz
import urllib2
import re
from xml.etree import ElementTree
def get_oauth():
inifile = ConfigParser.SafeConfigParser()
inifile.read("./config.ini")
CONSUMER_KEY = (inifile.get("Consumer Key", "CONSUMER_KEY"))
CONSUMER_SECRET = (inifile.get("Consumer Key", "CONSUMER_SECRET"))
ACCESS_TOKEN = (inifile.get("Access Token", "ACCESS_TOKEN"))
ACCESS_TOKEN_SECRET = (inifile.get("Access Token", "ACCESS_TOKEN_SECRET"))
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
return tweepy.API(auth_handler=auth)
def get_mes():
pre_str = []
for line in open('message.txt', 'r'):
pre_str.append(line.strip("\n"))
random.shuffle(pre_str)
return pre_str[0]
def get_header_what_today():
d = datetime.datetime.now(pytz.timezone('Asia/Tokyo'))
return d.strftime("今日(%m/%d)の出来事\n")
def get_what_today():
url = 'http://ja.wikipedia.org/w/api.php?format=xml&action=query&prop=revisions&titles=Template:今日は何の日&rvprop=content'
etree = ElementTree.fromstring(urllib2.urlopen(url).read())
list = etree.find(".//rev").text.encode('utf-8').splitlines()
num = random.randint(0, (len(list) - 1))
str = list[num]
return get_header_what_today() + replace_what_today(str, num)
def replace_what_today(mes, num):
mes = mes.replace("*", str(num + 1) + ".")
pattern = r"\[\[.*?\|"
mes = re.sub(pattern, "", mes)
mes = mes.replace("[", "")
mes = mes.replace("]", "")
return mes
def main():
api = get_oauth()
if random.randint(0, 2) == 0:
api.update_status(get_mes())
else:
api.update_status(get_what_today())
if __name__ == '__main__':
main()
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.