Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
HKLHaoBin authored Oct 5, 2024
1 parent fb5aab9 commit 99b63b7
Showing 1 changed file with 53 additions and 12 deletions.
65 changes: 53 additions & 12 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
#!pip install --upgrade appbuilder-sdk qianfan nest_asyncio discord.py redis
# 必须放置在文件顶部
import os
import re
import socket
import qianfan
import discord
import asyncio
import nest_asyncio
import appbuilder
import logging

print(dir(appbuilder))
nest_asyncio.apply()

# 设置环境变量以进行认证
QIANFAN_ACCESS_KEY = os.environ["QIANFAN_ACCESS_KEY"]
QIANFAN_SECRET_KEY = os.environ["QIANFAN_SECRET_KEY"]
Expand All @@ -20,11 +23,13 @@
lock = asyncio.Lock()

chat_comp = qianfan.ChatCompletion()

# Discord 配置
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)


async def main():
try:
await client.start(APPBUILDER_TOKEN)
Expand All @@ -35,6 +40,7 @@ async def main():
except Exception as e:
logging.error(f'Unexpected error: {e}')


powerOff = False
powerOff_user = ""
powerOff_user_input = ""
Expand All @@ -43,25 +49,29 @@ async def main():
# 设置日志记录
logging.basicConfig(level=logging.INFO)

# 设置指定的频道ID
# 你可以在这里设置指定的频道ID
target_channel_id = 1273112599885647883 # 替换为你的实际频道ID


def get_ip_address():
hostname = socket.gethostname() # 获取主机名
ip_address = socket.gethostbyname(hostname) # 获取IP地址
return ip_address


@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
# 获取指定频道
channel = client.get_channel(target_channel_id)
# if channel:
# await channel.send("""fairy 启动 !""")


@client.event
async def on_disconnect():
logging.warning('Bot has disconnected.')

@client.event
async def on_error(event, *args, **kwargs):
logging.error(f'Error occurred in {event}: {args} - {kwargs}')

@client.event
async def on_message(message):
Expand All @@ -81,6 +91,7 @@ async def on_message(message):
return

if "论坛内容" in user_input and "评论内容" in user_input:
# 从AppBuilder控制台获取已发布应用的ID
REVIEW_APP_ID = os.environ["REVIEW_APP_ID"]

try:
Expand All @@ -89,6 +100,7 @@ async def on_message(message):
conversation_id = app_builder_client.create_conversation()
resp = app_builder_client.run(conversation_id, user_input)
await message.channel.send(resp.content.answer)
print(resp.content.answer)
except Exception as e:
logging.error(f"API request failed: {e}")
await message.channel.send("等待,发生了错误。")
Expand All @@ -97,19 +109,22 @@ async def on_message(message):
if "!wait!" in user_input:
user_input = re.sub(r"!wait!", "", user_input).strip()
Post_review += user_input
print(Post_review)
await message.channel.send("继续")
print("继续")
return

if "!end!" in user_input:
user_input = re.sub(r"!end!", "", user_input).strip()
Post_review += user_input

# 从AppBuilder控制台获取已发布应用的ID
try:
REVIEW_APP_ID = os.environ["REVIEW_APP_ID"]
app_builder_client = appbuilder.AppBuilderClient(REVIEW_APP_ID)
conversation_id = app_builder_client.create_conversation()
resp = app_builder_client.run(conversation_id, Post_review)
await message.channel.send(resp.content.answer)
print(resp.content.answer)
except Exception as e:
logging.error(f"Failed to process request: {e}")
await message.channel.send(" 艹! 出错了! 联系一下<@1140530007555444797>")
Expand All @@ -118,14 +133,26 @@ async def on_message(message):

if "fairy" in user_input or "1275123343376515214" in user_input:
if powerOff:
if username in ["haobinoo", "nahida_buer", "furina1048576", "myitian"] and "启动" in user_input:
if (
(username == "haobinoo" and "启动" in user_input) or
(username == "nahida_buer" and "启动" in user_input) or
(username == "furina1048576" and "启动" in user_input) or
(username == "myitian" and "启动" in user_input)
):
powerOff = False
await message.channel.send("我的好主人,我回来了!")
return
await message.channel.send(f"Fairy已因 @{powerOff_user} 说了 '{powerOff_user_input}' 导致关闭,现无法回答问题,请等待 <@1140530007555444797> <@1165292898699464725> <@1130876908750512228> <@964838656420491285>。")
await message.channel.send(
f"Fairy已因 @{powerOff_user} 说了 '{powerOff_user_input}' 导致关闭,"
f"现无法回答问题,请等待 <@1140530007555444797> "
f"<@1165292898699464725> <@1130876908750512228> <@964838656420491285>。"
)
return

if any(word in user_input for word in ["再见!", "滚!", "拜拜!", "离开!", "关闭!", "sb!", "关机!", "智障!"]):
if any(
word in user_input
for word in ["再见!", "滚!", "拜拜!", "离开!", "关闭!", "sb!", "关机!", "智障!"]
):
await message.channel.send("再见!")
powerOff_user = username
powerOff_user_input = user_input
Expand Down Expand Up @@ -153,31 +180,44 @@ async def on_message(message):
print(f"匹配到 '@ + int' 的字符串: {text}")

# 发起对话请求
user_input = re.sub(r"<@\d+>|<[a-zA-Z]+:[a-zA-Z]+:\d+>|<:[a-zA-Z]+:\d+>", "", user_input).strip()
# 移除类似 <@userID> 的模式
user_input = re.sub(
r"<@\d+>|<[a-zA-Z]+:[a-zA-Z]+:\d+>|<:[a-zA-Z]+:\d+>",
"",
user_input
).strip()
print("过滤后:", user_input)
response = await make_qianfan_request(username, user_input)
print(response)
await message.channel.send(response)
except Exception as e:
logging.error(f"Error occurred while processing message: {message.content}, error: {e}")
logging.error(
f"Error occurred while processing message: {message.content}, error: {e}"
)


async def make_qianfan_request(username, user_input):
try:
# 从AppBuilder控制台获取已发布应用的ID
CHAT_APP_ID = os.environ["CHAT_APP_ID"]

app_builder_client = appbuilder.AppBuilderClient(CHAT_APP_ID)
conversation_id = await asyncio.to_thread(app_builder_client.create_conversation)
resp = await asyncio.to_thread(app_builder_client.run, conversation_id, user_input)
resp = await asyncio.to_thread(
app_builder_client.run, conversation_id, user_input
)
content = resp.content.answer

if username == "haobinoo":
return "我的好主人," + content
return content

except Exception as e:
# 记录错误并返回默认消息
logging.error(f"Error during Qianfan API request: {e}")
return "等待,发生了错误。"


@client.event
async def on_error(event, *args, **kwargs):
logging.error(f"Error occurred in {event}: {args} - {kwargs}")
Expand All @@ -188,5 +228,6 @@ async def on_error(event, *args, **kwargs):
except Exception as e:
logging.error(f"Reconnection failed: {e}")


# 启动Bot
asyncio.run(main())

0 comments on commit 99b63b7

Please sign in to comment.