Skip to content

Commit

Permalink
More fixes for pep8 standards
Browse files Browse the repository at this point in the history
  • Loading branch information
TomCasavant committed May 5, 2024
1 parent 9d55680 commit aba50e0
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 88 deletions.
125 changes: 64 additions & 61 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,30 @@
"""
A bot that interacts with a Mastodon compatible API, plays gameboy games via a Poll
"""

import os
import random
import time

import toml
from mastodon import Mastodon
from requests.exceptions import RequestException

from gb import Gameboy


class Bot:
"""
A Mastodon-API Compatible bot that handles gameboy gameplay through polls
"""

def __init__(self, config_path="config.toml"):
# If config_path is not provided, use the config.toml file in the same
# directory as the script
# Get the directory of the current script
self.script_dir = os.path.dirname(os.path.realpath(__file__))
config_path = os.path.join(self.script_dir, "config.toml")
with open(config_path, "r") as config_file:
with open(config_path, "r", encoding="utf-8") as config_file:
self.config = toml.load(config_file)
self.mastodon_config = self.config.get("mastodon", {})
self.gameboy_config = self.config.get("gameboy", {})
Expand All @@ -27,34 +35,35 @@ def __init__(self, config_path="config.toml"):
self.gameboy = Gameboy(rom, True)

def simulate(self):
"""Simulates gameboy actions by pressing random buttons, useful for testing"""
while True:
# print(self.gameboy.is_running())
if True:
# self.gameboy.random_button()
buttons = {
"a": self.gameboy.a,
"b": self.gameboy.b,
"start": self.gameboy.start,
"select": self.gameboy.select,
"up": self.gameboy.dpad_up,
"down": self.gameboy.dpad_down,
"right": self.gameboy.dpad_right,
"left": self.gameboy.dpad_left,
"random": self.gameboy.random_button,
"tick": "tick",
}
# self.gameboy.random_button()
print(buttons)
press = input("Button: ")
if press == "tick":
for i in range(60):
self.gameboy.pyboy.tick()
else:
buttons[press]()
# self.gameboy.random_button()
buttons = {
"a": self.gameboy.a,
"b": self.gameboy.b,
"start": self.gameboy.start,
"select": self.gameboy.select,
"up": self.gameboy.dpad_up,
"down": self.gameboy.dpad_down,
"right": self.gameboy.dpad_right,
"left": self.gameboy.dpad_left,
"random": self.gameboy.random_button,
"tick": "tick",
}
# self.gameboy.random_button()
print(buttons)
press = input("Button: ")
if press == "tick":
for _ in range(60):
self.gameboy.pyboy.tick()
# time.sleep(1)
else:
buttons[press]()
self.gameboy.pyboy.tick()
# time.sleep(1)

def random_button(self):
"""Chooses a random button and presses it on the gameboy"""
buttons = {
"a": self.gameboy.a,
"b": self.gameboy.b,
Expand All @@ -72,13 +81,15 @@ def random_button(self):
return random_button

def login(self):
"""Logs into the mastodon server using config credentials"""
server = self.mastodon_config.get("server")
print(f"Logging into {server}")
return Mastodon(
access_token=self.mastodon_config.get("access_token"), api_base_url=server
)

def post_poll(self, status, options, expires_in=60 * 60, reply_id=None):
"""Posts a poll to Mastodon compatible server"""
poll = self.mastodon.make_poll(
options, expires_in=expires_in, hide_totals=False
)
Expand All @@ -87,34 +98,41 @@ def post_poll(self, status, options, expires_in=60 * 60, reply_id=None):
)

def save_ids(self, post_id, poll_id):
"""Saves post IDs to a text file"""
# Get the directory of the current script
script_dir = os.path.dirname(os.path.realpath(__file__))
ids_loc = os.path.join(script_dir, "ids.txt")
with open(ids_loc, "w") as file:
with open(ids_loc, "w", encoding="utf-8") as file:
file.write(f"{post_id},{poll_id}")

def read_ids(self):
"""Reads IDs from the text file"""
try:
# Get the directory of the current script
script_dir = os.path.dirname(os.path.realpath(__file__))
ids_loc = os.path.join(script_dir, "ids.txt")
with open(ids_loc, "r") as file:
with open(ids_loc, "r", encoding="utf-8") as file:
content = file.read()
if content:
post_id, poll_id = content.split(",")
return post_id, poll_id
except FileNotFoundError:
return None, None

return None

def pin_posts(self, post_id, poll_id):
"""Pin posts to profile"""
self.mastodon.status_pin(poll_id)
self.mastodon.status_pin(post_id)

def unpin_posts(self, post_id, poll_id):
"""Unpin posts from profile"""
self.mastodon.status_unpin(post_id)
self.mastodon.status_unpin(poll_id)

def take_action(self, result):
"""Presses button on gameboy based on poll result"""
buttons = {
"up ⬆️": self.gameboy.dpad_up,
"down ⬇️": self.gameboy.dpad_down,
Expand All @@ -133,16 +151,20 @@ def take_action(self, result):
else:
print(f"No action defined for '{result}'.")

def retry_mastodon_call(self, func, retries=5, interval=10, *args, **kwargs):
def retry_mastodon_call(self, func, *args, retries=5, interval=10, **kwargs):
"""Continuously retries mastodon call, useful for servers with timeout issues"""
for _ in range(retries):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Failure to execute {e}")
except RequestException as e:
print(f"Failure to execute {func.__name__}: {e}")
time.sleep(interval)
return False # Failed to execute

def run(self):
"""
Runs the main gameplay, reads mastodon poll result, takes action, generates new posts
"""
self.gameboy.load()
post_id, poll_id = self.read_ids()
top_result = None
Expand Down Expand Up @@ -195,26 +217,18 @@ def run(self):
media_ids = [media["id"], previous_media["id"]]
except BaseException:
media_ids = [media["id"]]
# try:
# media = self.mastodon.media_post(image, description='Screenshot of pokemon gold')
# except:
# time.sleep(45)
# media = self.mastodon.media_post(image, description='Screenshot of pokemon gold')
# time.sleep(50)

post = self.retry_mastodon_call(
self.mastodon.status_post,
retries=5,
interval=10,
status=f"Previous Action: {top_result}\n\n#pokemon #gameboy #nintendo #FediPlaysPokemon",
status=(
f"Previous Action: {top_result}\n\n"
"#pokemon #gameboy #nintendo #FediPlaysPokemon"
),
media_ids=[media_ids],
)
# try:
# post = self.mastodon.status_post(f"Previous Action: {top_result}\n\n#pokemon #gameboy #nintendo", media_ids=[media['id']])
# except:
# time.sleep(30)
# post = self.mastodon.status_post(f"Previous Action:
# {top_result}\n\n#pokemon #gamebody #nintendo",
# media_ids=[media['id']])

poll = self.retry_mastodon_call(
self.post_poll,
retries=5,
Expand All @@ -233,26 +247,14 @@ def run(self):
reply_id=post["id"],
)

# ry:
# poll = self.post_poll("Vote on the next action:", ["Up ⬆️", "Down ⬇️", "Right ➡️ ", "Left ⬅️", "🅰", "🅱", "Start", "Select"], reply_id=post['id'])
# except:
# time.sleep(30)
# poll = self.post_poll("Vote on the next action:", ["Up ⬆️", "Down ⬇️", "Right ➡️ ", "Left ⬅️", "🅰", "🅱", "Start", "Select"], reply_id=post['id'])

self.retry_mastodon_call(
self.pin_posts,
retries=5,
interval=10,
post_id=post["id"],
poll_id=poll["id"],
)
# try:
# self.pin_posts(post['id'], poll['id'])
# except:
# time.sleep(30)
# self.pin_posts(post['id'], poll['id'])

# result = self.gameboy.build_gif("gif_images")
result = False
if result:
gif = self.retry_mastodon_call(
Expand All @@ -277,10 +279,11 @@ def run(self):
self.gameboy.save()

def test(self):
"""Method used for testing"""
self.gameboy.load()
self.gameboy.get_recent_frames("screenshots", 25)
# self.gameboy.build_gif("gif_images")
"""while True:
while True:
inp = input("Action: ")
buttons = {
"up": self.gameboy.dpad_up,
Expand All @@ -290,12 +293,12 @@ def test(self):
"a": self.gameboy.a,
"b": self.gameboy.b,
"start": self.gameboy.start,
"select": self.gameboy.select
"select": self.gameboy.select,
}
# Perform the corresponding action
if inp.lower() in buttons:
action = buttons[inp.lower()]
#self.gameboy.tick()
# self.gameboy.tick()
action()
frames = self.gameboy.loop_until_stopped()
if frames > 51:
Expand All @@ -306,9 +309,9 @@ def test(self):
else:
print(f"No action defined for '{inp}'.")
self.gameboy.save()
#self.gameboy.build_gif("gif_images")
#self.take_action(inp)
#self.gameboy.tick(300)"""
# self.gameboy.build_gif("gif_images")
# self.take_action(inp)
# self.gameboy.tick(300)


if __name__ == "__main__":
Expand Down
Loading

0 comments on commit aba50e0

Please sign in to comment.