Here’s the updated script with the sender username:
MAX_MESSAGES = 1000 # Optional limit for testing
SECONDS_BETWEEN_MESSAGES = 3 # 3 second interval
SENDER_USERNAME = "coco"
message_sender = User.find_by(username: SENDER_USERNAME)
if message_sender.nil?
Rails.logger.error "Sender user '#{message_sender_username}' not found!"
exit
end
Rails.logger.info "Starting bulk message script..."
# Define the content of your message
message_title = "Welcome to Our Community"
message_body = "Hello! We're so excited to have you here. Let us know if you have any questions!"
# Fetch users ordered by last seen
users = User.where(active: true)
.where.not(staged: true) # Exclude staged users
.order(last_seen_at: :desc)
.limit(MAX_MESSAGES)
Rails.logger.info "Found #{users.count} active users to message."
users.each_with_index do |user, index|
begin
Rails.logger.info "Queuing message for #{user.username} (#{index + 1}/#{users.count})..."
PostCreator.create!(
message_sender,
title: message_title,
raw: message_body,
archetype: Archetype.private_message,
target_usernames: user.username,
skip_validations: true
)
Rails.logger.info "Message successfully queued for #{user.username}."
# Wait for the specified interval before processing the next user
sleep(SECONDS_BETWEEN_MESSAGES)
rescue => e
Rails.logger.error "Failed to send message to #{user.username}: #{e.message}"
end
end
Rails.logger.info "Bulk message script completed!"