使用 SQLite 数据库构建 Telegram 自动记账机器人
当编写自动记账机器人时,您可以使用 SQLite 数据库来存储记账数据。以下是在先前给出的示例代码中添加 SQLite 数据库操作的修改版本:
import logging
import sqlite3
from sqlite3 import Error
from telegram import Update
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
# 设置日志记录级别
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
# Telegram Bot Token
TOKEN = 'YOUR_TELEGRAM_TOKEN'
# SQLite 数据库文件路径
DB_PATH = 'expenses.db'
# 创建数据库连接
def create_connection():
conn = None
try:
conn = sqlite3.connect(DB_PATH)
print('成功连接到 SQLite 数据库')
return conn
except Error as e:
print(e)
# 创建记账表
def create_expenses_table(conn):
try:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
amount REAL NOT NULL,
description TEXT NOT NULL
);
''')
conn.commit()
print('成功创建记账表')
except Error as e:
print(e)
# 处理/start命令
def start(update: Update, context: CallbackContext) -> None:
update.message.reply_text('欢迎使用自动记账机器人!')
# 处理记账命令
def record_expense(update: Update, context: CallbackContext) -> None:
# 获取记账信息
expense = update.message.text.split('/record ')[1]
# 连接数据库
conn = create_connection()
# 创建记账表(如果不存在)
create_expenses_table(conn)
# 插入记账记录
cursor = conn.cursor()
cursor.execute('INSERT INTO expenses (amount, description) VALUES (?, ?)', (expense, 'Expense Description'))
conn.commit()
# 回复确认消息
update.message.reply_text('已记账:{}'.format(expense))
# 处理未知命令
def unknown(update: Update, context: CallbackContext) -> None:
update.message.reply_text('未知命令,请重试!')
def main() -> None:
# 创建 Updater 对象,并传入 Telegram Bot 的 Token
updater = Updater(TOKEN)
# 获取 Dispatcher 对象
dispatcher = updater.dispatcher
# 添加处理/start 命令的 handler
dispatcher.add_handler(CommandHandler('start', start))
# 添加处理记账命令的 handler
dispatcher.add_handler(MessageHandler(Filters.regex(r'/record .*'), record_expense))
# 添加处理未知命令的 handler
dispatcher.add_handler(MessageHandler(Filters.command, unknown))
# 启动 Bot
updater.start_polling()
# 让 Bot 一直运行,直到按下 Ctrl-C 停止
updater.idle()
if __name__ == '__main__':
main()
在这个示例代码中,我添加了以下功能:
- 创建了一个名为
create_connection的函数来建立与 SQLite 数据库的连接。 - 创建了一个名为
create_expenses_table的函数,在连接到数据库后创建expenses表(如果不存在)。 - 在
record_expense函数中,我使用create_connection函数来建立数据库连接,并在连接成功后调用create_expenses_table函数来创建记账表(如果不存在)。 - 在
record_expense函数中,我使用数据库连接插入了一条新的记账记录。
请注意,这只是一个简单的示例,数据库的使用方式可以根据您的需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/N0C 著作权归作者所有。请勿转载和采集!