Certainly! Instead of creating a new handle_new_post
method, we can modify the existing schedule_reply
method in lib/ai_bot/playground.rb to handle the new requirements. Here’s the updated code:
def self.schedule_reply(post)
return if post.user.bot?
bot_user = nil
persona = nil
if post.reply_to_post_number.present?
replied_to_post = Post.find_by(topic_id: post.topic_id, post_number: post.reply_to_post_number)
if replied_to_post.user.bot?
# User replied to bot, continue with reply
bot_user = replied_to_post.user
persona = AiPersona.find_by(user: post.user, name: replied_to_post.ai_persona_name)
else
# User replied to another user, don't reply
return
end
end
bot_user ||= post.topic.topic_allowed_users.where(user_id: DiscourseAi::AiBot::EntryPoint::BOT_USER_IDS).first&.user
persona ||= DiscourseAi::AiBot::Personas::Persona.find_by(user: post.user, id: post.topic.custom_fields["ai_persona_id"])
return unless bot_user && persona
bot = DiscourseAi::AiBot::Bot.as(bot_user, persona: persona.new)
DiscourseAi::AiBot::Playground.new(bot).reply_to(post)
end
And here are the updated tests for spec/lib/ai_bot/playground_spec.rb:
require 'rails_helper'
describe DiscourseAi::AiBot::Playground do
fab!(:user) { Fabricate(:user) }
fab!(:bot_user) { Fabricate(:user, id: DiscourseAi::AiBot::EntryPoint::GPT4_ID) }
fab!(:persona) { DiscourseAi::AiBot::Personas::Persona.create(user: user, name: 'Test Persona') }
before do
SiteSetting.ai_bot_enabled = true
SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:everyone]
end
describe '.schedule_reply' do
fab!(:topic) { Fabricate(:private_message_topic, topic_allowed_users: [user, bot_user]) }
fab!(:bot_post) { Fabricate(:post, topic: topic, user: bot_user) }
fab!(:user_post) { Fabricate(:post, topic: topic, user: user) }
it 'does not reply when user replies to another user' do
reply = Fabricate(:post, topic: topic, user: user, reply_to_post_number: user_post.post_number)
expect(DiscourseAi::AiBot::Playground).not_to receive(:new)
DiscourseAi::AiBot::Playground.schedule_reply(reply)
end
it 'replies as the replied-to persona when user replies to bot' do
persona.update!(user: bot_user)
bot_post.update!(raw: "This is the Test Persona")
reply = Fabricate(:post, topic: topic, user: user, reply_to_post_number: bot_post.post_number)
playground = DiscourseAi::AiBot::Playground.new(nil)
expect(DiscourseAi::AiBot::Playground).to receive(:new).and_return(playground)
expect(playground).to receive(:reply_to).with(reply)
DiscourseAi::AiBot::Playground.schedule_reply(reply)
end
end
end
The changes are similar to the previous version, but now we’re modifying the existing schedule_reply
method instead of creating a new one.
The tests remain the same, but they now call schedule_reply
instead of handle_new_post
.
Let me know if you have any further questions or if you’d like me to make any other changes!