|
| 1 | +# Фоновая задача для вступления бота в Telegram канал |
| 2 | +# Запускается после добавления канала в систему |
| 3 | +class Channels::BotJoinJob < ApplicationJob |
| 4 | + queue_as :channels |
| 5 | + retry_on StandardError, wait: :exponentially_longer, attempts: 3 |
| 6 | + |
| 7 | + def perform(channel_id) |
| 8 | + with_error_context(channel_id: channel_id, action: 'bot_join') do |
| 9 | + channel = Channel.find(channel_id) |
| 10 | + |
| 11 | + Rails.logger.info "Starting bot join process for channel #{channel.username}" |
| 12 | + |
| 13 | + # Обновляем статус на joining |
| 14 | + channel.start_joining! |
| 15 | + |
| 16 | + # Пытаемся вступить в канал |
| 17 | + success = attempt_to_join_channel(channel) |
| 18 | + |
| 19 | + if success |
| 20 | + channel.mark_as_joined! |
| 21 | + notify_admins_success(channel) |
| 22 | + Rails.logger.info "Bot successfully joined channel #{channel.username}" |
| 23 | + else |
| 24 | + error_message = extract_error_message(success) |
| 25 | + channel.mark_as_join_failed!(error_message) |
| 26 | + notify_admins_failure(channel, error_message) |
| 27 | + Rails.logger.error "Bot failed to join channel #{channel.username}: #{error_message}" |
| 28 | + end |
| 29 | + end |
| 30 | + end |
| 31 | + |
| 32 | + private |
| 33 | + |
| 34 | + def attempt_to_join_channel(channel) |
| 35 | + begin |
| 36 | + # Инициализируем клиент |
| 37 | + bot = Telegram.bots[:default] |
| 38 | + |
| 39 | + # Для публичных каналов бот может просто начать следить |
| 40 | + # через webhook без дополнительного вступления |
| 41 | + chat_id = channel.telegram_id |
| 42 | + |
| 43 | + # Проверяем доступность канала |
| 44 | + chat_info = bot.get_chat(chat_id: chat_id) |
| 45 | + |
| 46 | + if chat_info['ok'] |
| 47 | + Rails.logger.info "Channel #{channel.username} is accessible to bot" |
| 48 | + true |
| 49 | + else |
| 50 | + error_code = chat_info['error_code'] || 'unknown' |
| 51 | + error_description = chat_info['description'] || 'Unknown error' |
| 52 | + |
| 53 | + Rails.logger.warn "Cannot access channel #{channel.username}: #{error_code} - #{error_description}" |
| 54 | + { error_code: error_code, error_description: error_description } |
| 55 | + end |
| 56 | + |
| 57 | + rescue Telegram::Bot::Error => e |
| 58 | + Rails.logger.error "Telegram API error for channel #{channel.username}: #{e.message}" |
| 59 | + { error_code: 'telegram_api_error', error_description: e.message } |
| 60 | + rescue StandardError => e |
| 61 | + Rails.logger.error "Unexpected error for channel #{channel.username}: #{e.message}" |
| 62 | + { error_code: 'unexpected_error', error_description: e.message } |
| 63 | + end |
| 64 | + end |
| 65 | + |
| 66 | + def extract_error_message(result) |
| 67 | + return 'Unknown error' if result == true |
| 68 | + return result[:error_description] if result.is_a?(Hash) && result[:error_description] |
| 69 | + 'Failed to join channel' |
| 70 | + end |
| 71 | + |
| 72 | + def notify_admins_success(channel) |
| 73 | + # TODO: Implement admin notifications in stage 4 |
| 74 | + Rails.logger.info "Bot successfully joined channel: #{channel.username} (#{channel.title})" |
| 75 | + end |
| 76 | + |
| 77 | + def notify_admins_failure(channel, error_message) |
| 78 | + # TODO: Implement admin notifications in stage 4 |
| 79 | + Rails.logger.error "Bot failed to join channel #{channel.username}: #{error_message}" |
| 80 | + end |
| 81 | +end |
0 commit comments