mirror of
https://github.com/looching/cantonese_toot.git
synced 2026-04-06 03:15:02 +08:00
76 lines
2.0 KiB
Python
76 lines
2.0 KiB
Python
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():
|
||
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()
|