Skip to content

Instantly share code, notes, and snippets.

@nomunomu0504
Last active November 17, 2022 05:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nomunomu0504/3d99d3a8c255cb79a32e91de3388e7cc to your computer and use it in GitHub Desktop.
Save nomunomu0504/3d99d3a8c255cb79a32e91de3388e7cc to your computer and use it in GitHub Desktop.
TwitterでLaTex投げたら画像として投稿してくれる
# -*- coding:utf-8 -*-
import datetime
import json
import re
import signal
import sys
import html
import requests
from datetime import timedelta
from requests_oauthlib import OAuth1Session
from tweepy.auth import OAuthHandler
from tweepy.streaming import StreamListener, Stream
consumerKey = 'YOUR_CONSUMER_KEY'
consumerSecret = 'YOUR_CONSUMER_SECRET'
accessToken = 'YOUR_ACCESS_TOKEN'
accessTokenSecret = 'YOUR_ACCESS_TOKEN_SECRET'
mediaUploadAddress = 'https://upload.twitter.com/1.1/media/upload.json'
favoTwiAddress = 'https://api.twitter.com/1.1/favorites/create.json'
tweetAddress = 'https://api.twitter.com/1.1/statuses/update.json'
profileUpdateAddress = 'https://api.twitter.com/1.1/account/update_profile.json'
imageAddress = 'https://t.co/%s'
auth = OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)
twitter = OAuth1Session(consumerKey, consumerSecret, accessToken, accessTokenSecret)
file = None
def killer(num, frame):
"""
UNIXシグナルのハンドラ
引数は2つ・番号とフレームオブジェクト
"""
print('killer(): %d, %s' % (num, str(frame)))
sys.exit(0)
def upload_letax_image(tax_text):
base_url = 'https://chart.apis.google.com/chart?cht=tx&chs=50&chl='
base_dir = "LaTex/"
base_file_name = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S') + ".png"
print("initialized variants.")
try:
url = base_url + tax_text
print("url: %s" % url)
res = requests.get(url, stream=True)
print("Create Requests.")
if res.status_code == 200:
print("Request Successed.")
with open(base_dir + base_file_name, 'wb') as img_file:
for chunk in res.iter_content(chunk_size=1024):
img_file.write(chunk)
else:
print("download failed.")
print("download Successed.")
files = {"media": open(base_dir + base_file_name, 'rb')}
req_media = twitter.post(mediaUploadAddress, files=files)
if req_media.status_code != 200:
print("media_upload_failed: %s", req_media.text)
exit()
print("media upload Successed.")
media_id = json.loads(req_media.text)['media_id']
except Exception as ex:
print(ex)
return media_id
class LaTex_Creater(StreamListener):
def on_connect(self):
print('on_connect.')
def on_status(self, status):
try:
# Ubuntuの時は気づかなかったんだけど、Windowsで動作確認してたら
# created_atはUTC(世界標準時)で返ってくるので日本時間にするために9時間プラスする。
status.created_at += timedelta(hours=9)
# 1tweetの区切り
print('--------------------')
print(u"{id}: {screen_name}({name})\n {tweet}".format(
id=status.id,
screen_name=status.author.screen_name,
name=status.author.name,
tweet=status.text
))
# tweetのjson化したデータを整形する( textベース )
# (unicode表記なし -> 日本語は日本語のまま
# result = json.dumps(status._json, ensure_ascii=False, indent=4).encode('utf8')
# tweetのjsonを抽出
tweet_json = status._json
# tweetに含まれているuserの抽出
to_reply_users = tweet_json['entities']['user_mentions']
# tweetがreplyのとき
if to_reply_users:
# 抽出したuserのscreen_nameを「@」付きで変数に格納していく
for to_reply_user in to_reply_users:
if to_reply_user['screen_name'] == u'YOUR_SCREEN_NAME':
# @user以降のテキストpoint
after_indices = to_reply_user['indices'][1]
tax = tweet_json['extended_tweet']['full_text'][after_indices:]
isexec = re.search('create_latex', tax)
if isexec:
# create_latexを削除
tax = tax.replace('create_latex', '')
# pmatrixはgoogle_chart_apiでは使えないのでarrayに変更
tax = tax.replace('pmatrix', 'array')
# 行列用の括弧を追加
tax = tax.replace('\\begin', '\left(\\begin')
tax = tax.replace('\end{array}', '\end{array}\\right)')
# google chart api用に文字を変更
tax = tax.replace('&', '%26')
print("before call upload_letax_image")
media_id = upload_letax_image(tax)
print("after call upload_letax_image")
tweetParams = {
'status': u'Created.',
'in_reply_to_status_id': status.id,
"media_ids": [media_id]
}
req = twitter.post(tweetAddress, params=tweetParams)
else:
pass
except Exception as err:
print(err)
class OnlyStream(StreamListener):
def on_connect(self):
print("Connected.")
def on_status(self, status):
print('--------------------')
print(u"{id}: {screen_name}({name})\n {tweet}".format(
id=status.id,
screen_name=status.author.screen_name,
name=status.author.name,
tweet=status.text
))
if __name__ == '__main__':
signal.signal(signal.SIGINT, killer)
stream = Stream(auth, LaTex_Creater(), secure=True)
stream.userstream()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment