diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..53d245f --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +toots.db +.python-version \ No newline at end of file diff --git a/send.py b/send.py index 82039a3..88d417d 100644 --- a/send.py +++ b/send.py @@ -1,30 +1,75 @@ from mastodon import Mastodon from loguru import logger import random +from peewee import * +# 数据库配置 +db = SqliteDatabase('toots.db') -# read all toots from file -with open('toots.txt', 'r') as f: - toots = f.read().split('\n\n') +# 定义 Toot 模型 +class Toot(Model): + content = TextField(unique=True) + sent = BooleanField(default=False) + class Meta: + database = db +# Mastodon 配置 access_token = 'your access token' instance = 'https://mastodon.social' mastodon_cli = Mastodon( - access_token=access_token, api_base_url=instance) + access_token=access_token, api_base_url=instance) -#randomly choose a toot -toot = random.choice(toots) +def create_table(): + with db: + db.create_tables([Toot]) + logger.info("数据库表已创建") -# post toot -try: - mastodon_cli.toot(toot) - logger.info('Toot posted, %s' % toot) - # remove toot from file - with open('toots.txt', 'w') as f: - f.write('\n\n'.join(toots)) - # record toot - with open('toots_sent.txt', 'a') as f: - f.write('\n\n' + toot) -except Exception as e: - logger.error(e) +def insert_toots(): + with open('toots.txt', 'r', encoding='utf-8') as f: + content = f.read() + + toots = content.split('\n\n') + + with db.atomic(): + for toot in toots: + if toot.strip(): + Toot.get_or_create(content=toot.strip()) + logger.info(f"已插入 {len(toots)} 条 toot") + +def get_random_toot(): + unsent_toots = Toot.select().where(Toot.sent == False) + + if unsent_toots.count() == 0: + Toot.update(sent=False).execute() + unsent_toots = Toot.select().where(Toot.sent == False) + logger.info("所有 toot 已重置为未发送状态") + + return random.choice(unsent_toots) if unsent_toots.exists() else None + +def main(): + create_table() + insert_toots() + + random_toot = get_random_toot() + if random_toot: + logger.info("随机选择的 toot:") + logger.info(random_toot.content) + + # 发送 toot + try: + mastodon_cli.toot(random_toot.content) + logger.success(f'Toot 已发送: {random_toot.content}') + + # 标记 toot 为已发送 + random_toot.sent = True + random_toot.save() + logger.info("Toot 已标记为已发送") + except Exception as e: + logger.error(f"发送 toot 时出错: {e}") + else: + logger.warning("没有找到未发送的 toot,请确保数据库中有数据。") + +if __name__ == "__main__": + logger.add("cantonese.log") # 添加文件日志 + main()