Class: Heathrow::Sources::Discord

Inherits:
Object
  • Object
show all
Defined in:
lib/heathrow/sources/discord.rb

Constant Summary collapse

API_BASE =
'https://discord.com/api/v10'

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Discord

Returns a new instance of Discord.



14
15
16
# File 'lib/heathrow/sources/discord.rb', line 14

def initialize(source)
  @source = source
end

Instance Method Details

#can_reply?Boolean

Returns:

  • (Boolean)


166
167
168
# File 'lib/heathrow/sources/discord.rb', line 166

def can_reply?
  true
end

#descriptionObject



22
23
24
# File 'lib/heathrow/sources/discord.rb', line 22

def description
  'Fetch messages from Discord servers and DMs'
end

#fetch_messagesObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/heathrow/sources/discord.rb', line 26

def fetch_messages
  token = @source.config['token']
  is_bot = @source.config['is_bot'] || false
  channels = @source.config['channels'] || []
  guilds = @source.config['guilds'] || []
  fetch_limit = @source.config['fetch_limit'] || 50
  
  messages = []
  
  # Get state file to track last message IDs per channel
  heathrow_home = File.expand_path('~/.heathrow')
  state_file = File.join(heathrow_home, 'state', "discord_#{@source.id}.json")
  FileUtils.mkdir_p(File.dirname(state_file))
  
  last_messages = if File.exist?(state_file)
    JSON.parse(File.read(state_file))
  else
    {}
  end
  
  begin
    # If specific channels are provided, fetch from those
    if channels && !channels.empty?
      channels_list = channels.is_a?(String) ? channels.split(',').map(&:strip) : channels
      channels_list.each do |channel_id|
        # Get channel info to determine if it's a guild channel or DM
        channel_info = fetch_channel_info(token, channel_id, is_bot)
        
        if channel_info
          guild_id = channel_info['guild_id']
          channel_name = channel_info['name'] || channel_id
          
          # If it's a guild channel, get guild info
          if guild_id
            guild_info = fetch_guild_info(token, guild_id, is_bot)
            guild_name = guild_info ? guild_info['name'] : "Server"
            channel_messages = fetch_channel_messages(token, channel_id, last_messages[channel_id], fetch_limit, is_bot, guild_name, channel_name, guild_id)
          else
            # It's a DM channel
            channel_messages = fetch_channel_messages(token, channel_id, last_messages[channel_id], fetch_limit, is_bot)
          end
        else
          # Fallback if we can't get channel info
          channel_messages = fetch_channel_messages(token, channel_id, last_messages[channel_id], fetch_limit, is_bot)
        end
        
        messages.concat(channel_messages)
        
        # Update last message ID for this channel
        if channel_messages.any?
          last_messages[channel_id] = channel_messages.first[:external_id].split('_').last
        end
      end
    end
    
    # If guilds are provided, fetch all channels from those guilds
    if guilds && !guilds.empty?
      guilds_list = guilds.is_a?(String) ? guilds.split(',').map(&:strip) : guilds
      guilds_list.each do |guild_id|
        # Get guild info for proper naming
        guild_info = fetch_guild_info(token, guild_id, is_bot)
        guild_name = guild_info ? guild_info['name'] : "Guild #{guild_id}"
        
        guild_channels = fetch_guild_channels(token, guild_id, is_bot)
        guild_channels.each do |channel|
          next unless channel['type'] == 0  # Only text channels
          
          channel_id = channel['id']
          channel_messages = fetch_channel_messages(token, channel_id, last_messages[channel_id], fetch_limit, is_bot, guild_name, channel['name'], guild_id)
          messages.concat(channel_messages)
          
          # Update last message ID for this channel
          if channel_messages.any?
            last_messages[channel_id] = channel_messages.first[:external_id].split('_').last
          end
        end
      end
    end
    
    # If neither channels nor guilds specified, try to get DMs
    if channels.empty? && guilds.empty?
      dm_channels = fetch_dm_channels(token, is_bot)
      dm_channels.each do |channel|
        channel_id = channel['id']
        channel_messages = fetch_channel_messages(token, channel_id, last_messages[channel_id], fetch_limit, is_bot)
        messages.concat(channel_messages)
        
        # Update last message ID for this channel
        if channel_messages.any?
          last_messages[channel_id] = channel_messages.first[:external_id].split('_').last
        end
      end
    end
    
    # Save state
    File.write(state_file, JSON.generate(last_messages))
    
  rescue => e
    return [{
      source_id: @source.id,
      source_type: 'discord',
      sender: 'Discord',
      subject: 'Error',
      content: "Failed to fetch messages: #{e.message}",
      timestamp: Time.now.to_s,
      is_read: 0
    }]
  end
  
  messages
end

#nameObject



18
19
20
# File 'lib/heathrow/sources/discord.rb', line 18

def name
  'Discord'
end

#send_message(to, subject, body, in_reply_to = nil) ⇒ Object



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/heathrow/sources/discord.rb', line 170

def send_message(to, subject, body, in_reply_to = nil)
  config = @source.config.is_a?(String) ? JSON.parse(@source.config) : @source.config
  token = config['token']
  is_bot = config['is_bot'] != false
  
  # Debug log
  File.open('/tmp/heathrow_debug.log', 'a') do |f|
    f.puts "\n=== DISCORD SEND MESSAGE #{Time.now} ==="
    f.puts "To: #{to.inspect}"
    f.puts "Subject: #{subject.inspect}"
    f.puts "Body length: #{body.length}"
    f.puts "In reply to: #{in_reply_to.inspect}"
  end
  
  # Parse the recipient - could be channel ID or username
  channel_id = if to =~ /^\d+$/
    to  # Already a channel ID
  else
    # Try to extract channel ID from a formatted string like "#general (123456789)"
    if to =~ /\((\d+)\)/
      $1
    else
      return { success: false, message: "Discord: Need channel ID, got '#{to}'. Check the To: field in editor." }
    end
  end
  
  # Build the message
  message_data = {
    content: body
  }
  
  # If replying, add reference
  if in_reply_to
    message_data[:message_reference] = {
      message_id: in_reply_to
    }
  end
  
  # Send the message
  uri = URI("#{API_BASE}/channels/#{channel_id}/messages")
  request = Net::HTTP::Post.new(uri)
  request['Authorization'] = is_bot ? "Bot #{token}" : token
  request['Content-Type'] = 'application/json'
  request.body = message_data.to_json
  
  begin
    response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
      http.request(request)
    end
    
    if response.is_a?(Net::HTTPSuccess)
      { success: true, message: "Message sent to Discord" }
    else
      error_data = JSON.parse(response.body) rescue {}
      { success: false, message: "Failed to send: #{error_data['message'] || response.message}" }
    end
  rescue => e
    { success: false, message: "Send failed: #{e.message}" }
  end
end

#test_connectionObject



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/heathrow/sources/discord.rb', line 138

def test_connection
  config = @source.config.is_a?(String) ? JSON.parse(@source.config) : @source.config
  token = config['token']
  is_bot = config['is_bot'] != false
  
  begin
    # Try to get user info
    uri = URI("#{API_BASE}/users/@me")
    request = Net::HTTP::Get.new(uri)
    request['Authorization'] = is_bot ? "Bot #{token}" : token
    
    response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
      http.request(request)
    end
    
    if response.is_a?(Net::HTTPSuccess)
      user_data = JSON.parse(response.body)
      username = user_data['username']
      discriminator = user_data['discriminator']
      { success: true, message: "Connected as #{username}##{discriminator}" }
    else
      { success: false, message: "Failed to connect: #{response.code} #{response.message}" }
    end
  rescue => e
    { success: false, message: "Connection test failed: #{e.message}" }
  end
end