↑ | Notes |
← Previous | The Many Deaths of Daniel Jackson (Unfinished) |
→ Next | GaoGaiGar eyecatch gallery |
Tags | notes monogatarirobot python source |
Posted | 2020-08-24 |
Updated | 2023-05-07 |
This is the source code for twitter dot com slash monogatarirobot bot account. Visit the main page for a hastily written lowdown on how it all works. You'll need to supply your own keys and images! good luck!
# -*- coding: utf-8 -*-
'''
author;
𝚜𝚙𝚊𝚌𝚎 ☆ 𝚋𝚛𝚞𝚌𝚎 (@spacebruce)
needed;
pip install pause
pip install tweepy
instructions;
install python3
type the needed^ lines
put monogataribot.py in folder
put your twitter tokens in the config area below and change values as desired
click on monogataribot.py
???
profit
license;
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
http://www.wtfpl.net/about/
'''
import tweepy
import time
import sys
import pause
import datetime
import os.path
from glob import glob
print("Monogatari bot V2.5 r286 beta 3")
#login
Online = True #Set to False for offline debug mode
ApiKey = "GET YOUR OWN TOKENS"
ApiKeySecret = "PUT THEM HERE"
AccessToken = "YEAH"
AccessTokenSecret = "YOU"
# config goes here
Slogan = r"" # post caption
Path = "./**/**/*.jpg" # image search path/parameters. uses glob syntax (https://en.wikipedia.org/wiki/Glob_%28programming%29#Syntax). ".*.jpg" for same dir, "./images/*.jpg" for images subdir, etc
Interval = 10 # minutes between posts
DelayStart = False
IconFile = "\icon.jpg"
HeaderFile = "\header.jpg"
# functions
def Panic():
# api.update_status(ErrorMessage)
print(ErrorMessage)
Errors = 0
def GetFiles(rootPath, verbose):
foundfiles = sorted(filter(os.path.isfile, glob(rootPath)))
files = []
for item in foundfiles:
if (IconFile not in item) and (HeaderFile not in item):
files.append(item)
else:
if(verbose):
print("removed ", item)
return files
def SendTweet(message,filename):
Name = os.path.splitext(os.path.basename(filename))[0]
print("post", Name, filename)
if Online: # Offline mode always works
try:
# api.update_with_media(filename, status=Name)
file = api.media_upload(filename)
api.update_status(message + Name, media_ids = [file.media_id])
return True
except:
print("posting broke somewhere, trying again")
for e in sys.exc_info():
print(e)
return False
else:
return True
def ChangeIcon(path):
print("Icon change ", path)
if Online:
api.update_profile_image(path)
def ChangeHeader(path):
print("Header change ", path)
if Online:
api.update_profile_banner(path)
# initial state
StartIndex = 0
# load images
ImageList = GetFiles(Path, True)
ListLength = len(ImageList)
print(ListLength, "files")
# resume state
if not os.path.isfile("state.txt"):
with open("state.txt","w") as saveFile:
saveFile.write(ImageList[0])
print("Starting new state file")
else:
with open("state.txt","r") as saveFile:
line = saveFile.readlines()
lastImage = line[0]
lastImage.replace(r"//",r"/")
try:
StartIndex = ImageList.index(lastImage)
print("{0} : {1}", lastImage, ImageList[StartIndex])
except:
StartIndex = 0
print("invalid state - restart")
print("Resuming at " + ImageList[StartIndex])
# twitter login
if Online:
auth = tweepy.OAuth1UserHandler(ApiKey, ApiKeySecret, AccessToken, AccessTokenSecret)
api = tweepy.API(auth)
try:
api.verify_credentials()
print("twitter OK")
except:
print("twitter not OK, try again (", sys.exc_info()[0], ")")
sys.exit()
else:
print("Offline testing mode")
#post
LastDirectory = ""
while(True):
index = StartIndex
while(index < ListLength):
next = (index + 1) % ListLength
Now = datetime.datetime.now()
DoPost = True
ImageName = ""
while(DoPost):
try:
ImageName = ImageList[index]
print("file ", index, "/", ListLength-1)
sent = SendTweet(Slogan, ImageName)
if sent:
print("OK!")
try:
with open("state.txt","w") as saveFile:
if(next < index):
StartIndex = 0
ImageName = ImageList[next]
saveFile.write(ImageName)
except:
print("Progress not saved to file!! (", sys.exc_info()[0], ")")
DoPost = False #no need to retry
index = next
else:
print("Trying again")
except:
print("posting broke somewhere, trying again")
for e in sys.exc_info():
print(e)
if DoPost: # retry every 5 seconds after error
Now += datetime.timedelta(seconds = 5)
pause.until(Now)
else: #normal posting schedule
# Update icon paths
try:
Directory = os.path.dirname(ImageName)
# print("dir", Directory)
if (Directory != LastDirectory):
print("Directory changed to", Directory)
ChangeIcon(Directory + IconFile)
ChangeHeader(Directory + HeaderFile)
except:
print("can't update icons, error?")
LastDirectory = Directory
NewList = GetFiles(Path, False) #Reload DB
NewLength = len(NewList)
if NewLength != ListLength: #If DB changed
ImageList.clear() #clear out old (unneccersary?)
ImageList = NewList #Use new DB
print("Database change detected! Change delta : ", NewLength - ListLength, "(",NewLength,")")
ListLength = NewLength #Update length
newIndex = ImageList.index(ImageName)
if next != newIndex: #If point EARLIER than current post has been edited, reseek
print("Update post index pointer", index, "to", newIndex)
index = newIndex
minutes = 60 # on minute in seconds
time.sleep(minutes * Interval)
# pause.until(Now + datetime.timedelta(minutes = Interval)) #Delay for the rest of wait period
StartIndex = 0
print("Sequence restart!")