cantonese_toot/send.py

77 lines
2.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from mastodon import Mastodon
from loguru import logger
import random
from peewee import *
# 数据库配置
db = SqliteDatabase('toots.db')
# 定义 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)
def create_table():
with db:
db.create_tables([Toot])
logger.info("数据库表已创建")
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():
if not Toot.table_exists():
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()