用ChatGPT+TG Bot做一个会写小说的AI助手
用ChatGPT+TG Bot做一个会写小说的AI助手
附免费部署模板 | 支持多角色协作/续写/世界观设定
一、为什么要在Telegram里写小说?
Telegram Bot 作为创作工具具有独特优势:
✅ 即时灵感捕捉:随时用文字/语音记录灵感片段
✅ 沉浸式创作环境:无广告干扰的纯净写作空间
✅ 多设备同步:手机记录灵感 → 电脑端深度编辑
✅ 社群协作:通过群组功能实现多人共创
案例展示:
- @NovelAI_Bot:根据故事梗概自动生成3种不同风格的开篇
- @PlotWizardBot:用「三幕剧结构」智能优化剧情节奏
- @CoWriteBot:多人接力创作(每位作者续写300字)
二、系统架构设计
graph TD
A[用户输入] --> B{指令判断}
B -->|新建故事| C[调用ChatGPT生成设定]
B -->|续写请求| D[加载上下文+续写]
B -->|修改命令| E[执行文本替换/风格调整]
C --> F[保存到数据库]
D --> F
E --> F
F --> G[返回结果并格式化]
三、零基础搭建指南(Python版)
步骤1:注册并获取API密钥
Telegram Bot Token
- 对话@BotFather → /newbot → 记录token
OpenAI API Key
- 登录OpenAI平台 → 创建API Key
步骤2:准备代码模板
import os
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters
import openai
# 初始化API
openai.api_key = os.getenv("OPENAI_API_KEY")
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
# 初始化提示词模板
PROMPT_TEMPLATE = """
作为专业小说家,请根据以下要求创作:
类型:{genre}
视角:{pov}
风格类似:{style}
当前情节:{plot}
请续写800-1000字,保持{style}风格
"""
async def start(update: Update, context):
await update.message.reply_text("📖 请输入 /new 开始新故事")
async def new_story(update: Update, context):
# 引导用户输入参数
guide_text = """
🎬 请按顺序提供以下参数(用 | 分隔):
类型 | 视角 | 风格 | 初始情节
示例:武侠 | 第一人称 | 古龙 | 剑客推开客栈的门...
"""
await update.message.reply_text(guide_text)
async def generate_text(update: Update, context):
try:
# 解析用户输入
user_input = update.message.text.split(' | ')
genre, pov, style, plot = user_input
# 构建提示词
prompt = PROMPT_TEMPLATE.format(
genre=genre,
pov=pov,
style=style,
plot=plot
)
# 调用ChatGPT
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
temperature=0.7
)
# 发送生成结果
await update.message.reply_text(response.choices[0].message.content)
except Exception as e:
await update.message.reply_text(f"🚨 生成失败:{str(e)}")
if __name__ == "__main__":
application = Application.builder().token(TELEGRAM_TOKEN).build()
# 注册命令处理器
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("new", new_story))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, generate_text))
application.run_polling()
步骤3:免费部署到Replit
- 访问模板仓库 → Fork到你的账户
- 在Replit新建Python项目 → 导入仓库代码
设置环境变量:
TELEGRAM_TOKEN = '你的Bot Token' OPENAI_API_KEY = '你的OpenAI密钥'
- 点击Run → 保持浏览器标签页打开保持运行
四、核心功能扩展指南
功能1|多章节自动续写
# 添加上下文记忆功能
from collections import deque
context_memory = deque(maxlen=5)
async def continue_writing(update: Update, context):
# 将前文加入Prompt
previous_text = "\n".join(context_memory)
enhanced_prompt = f"前文回顾:{previous_text}\n\n请继续创作:"
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": enhanced_prompt}],
temperature=0.8
)
new_content = response.choices[0].message.content
context_memory.append(new_content)
await update.message.reply_text(new_content)
功能2|角色数据库管理
# 使用TinyDB保存角色设定
from tinydb import TinyDB
db = TinyDB('characters.json')
async def add_character(update: Update, context):
# 输入格式:角色名 | 年龄 | 性格 | 背景故事
parts = update.message.text.split(' | ')
db.insert({
'name': parts[0],
'age': parts[1],
'personality': parts[2],
'backstory': parts[3]
})
await update.message.reply_text("✅ 角色已存入数据库")
功能3|风格迁移改写
async def rewrite_style(update: Update, context):
# 指令格式:/rewrite 金庸
target_style = context.args[0]
original_text = update.message.reply_to_message.text
prompt = f"请将以下文字改写成{target_style}风格:\n{original_text}"
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
temperature=0.9
)
await update.message.reply_text(response.choices[0].message.content)
五、高级技巧:提升创作质量的秘诀
1. 温度值(Temperature)调节指南
温度值 | 适用场景 | 示例参数 |
---|---|---|
0.2 | 严谨历史小说 | temp=0.2 |
0.7 | 奇幻/科幻创作 | temp=0.7 |
1.0 | 实验性意识流 | temp=1.0 |
2. 自定义知识库增强
# 加载《故事写作大师课》知识库
with open('storytelling_knowledge.txt') as f:
expert_knowledge = f.read()
enhanced_prompt = f"""
根据以下写作原则:{expert_knowledge}
用户要求:{user_input}
请按照经典三幕剧结构创作:
第一幕(建制) → 第二幕(对抗) → 第三幕(解决)
"""
3. 敏感内容过滤系统
from openai.moderation import create
def content_filter(text):
response = openai.Moderation.create(input=text)
if response.results[0].flagged:
return "⚠️ 内容不符合安全策略,请调整后重试"
return text
# 在生成后调用
filtered_text = content_filter(generated_text)
六、免费替代方案(GPT-3.5版)
1. 代码修改点
- model="gpt-4"
+ model="gpt-3.5-turbo"
- temperature=0.7
+ temperature=0.5
2. Prompt优化技巧
# 添加详细的结构化指令
enhanced_prompt = """
[角色设定]
主角:林默,28岁考古学家
特征:右眼有异瞳,能看见古代幽灵
[情节要求]
1. 开场必须出现神秘文物
2. 包含一次反转
3. 结尾留有悬念
请根据以上大纲创作:
"""
七、常见问题解决
Q:生成内容过于模板化?
A:尝试:
1)添加「避免常见桥段」的负面提示
2)要求提供「反套路」设定
3)使用「if...then...」条件式指令
Q:如何处理长文本截断?
A:实现自动分片发送:
from telegram import InputMediaDocument
async def send_long_text(text):
chunks = [text[i:i+4000] for i in range(0, len(text), 4000)]
for chunk in chunks:
await update.message.reply_text(chunk)
部署模板获取:GitHub仓库地址
(包含完整代码+预设知识库+使用文档)
通过本教程,你已拥有一个24小时待命的AI创作助手。接下来可以尝试:
- 添加DALL·E 3插画生成功能
- 实现多语言版本切换
- 构建小说评分/读者反馈系统
分类:
实用教程
标签:
telegram实用教程电报机器人教程
版权申明
本文系作者 @admin 原创发布在telegram知识库站点。未经许可,禁止转载。
暂无评论数据