OverviewFilesCommitsIssuesDocsReleasesPeers

hypercore-kb / hyper-social / bridge-discord / lib / adapter.js

100 lines · javascript ref:
import { createEnvelope, TYPES, PLATFORMS } from 'bridge-envelope'

function discordToEnvelope (message) {
  // Skip bot messages
  if (message.author.bot) return null

  const author = message.author.tag || message.author.username
  const channel = message.channel.name || message.channelId
  const content = message.content || ''

  // Detect message type
  let type = TYPES.TEXT
  let mediaUrl = ''
  let mediaType = ''
  let replyTo = ''

  // Attachments
  const attachment = message.attachments?.first?.()
  if (attachment) {
    type = TYPES.MEDIA
    mediaUrl = attachment.url
    mediaType = attachment.contentType || ''
  }

  // Reply
  if (message.reference?.messageId) {
    replyTo = message.reference.messageId
    if (type === TYPES.TEXT) type = TYPES.REPLY
  }

  return createEnvelope({
    type,
    platform: PLATFORMS.DISCORD,
    author,
    content,
    channel,
    replyTo,
    mediaUrl,
    mediaType
  })
}

function keetToDiscord (keetMsg, bridgeIdentity) {
  if (keetMsg.memberId === bridgeIdentity) return null
  if (keetMsg.system) return null

  const name = keetMsg.name || 'anonymous'
  const text = keetMsg.text || ''
  if (!text.trim()) return null

  // Format for Discord — bold name prefix
  return {
    name,
    text: `**${name}** (Keet): ${text}`
  }
}

function envelopeToDiscordContent (envelope) {
  const platform = platformName(envelope.platform)
  const prefix = platform !== 'discord' ? `[${platform}] ` : ''
  const author = envelope.author || 'anonymous'

  switch (envelope.type) {
    case TYPES.TEXT:
    case TYPES.REPLY:
      return `${prefix}**${author}**: ${envelope.content}`
    case TYPES.MEDIA:
      return `${prefix}**${author}**: ${envelope.content || ''}\n${envelope.mediaUrl || ''}`
    case TYPES.REACTION:
      return `${prefix}*${author} reacted: ${envelope.content}*`
    case TYPES.SYSTEM:
      return `*${prefix}${envelope.content}*`
    default:
      return `${prefix}**${author}**: ${envelope.content}`
  }
}

function discordReactionToEnvelope (reaction, user) {
  return createEnvelope({
    type: TYPES.REACTION,
    platform: PLATFORMS.DISCORD,
    author: user.tag || user.username,
    content: reaction.emoji.name || reaction.emoji.toString(),
    channel: reaction.message.channel.name || reaction.message.channelId,
    replyTo: reaction.message.id
  })
}

function platformName (id) {
  const names = ['keet', 'irc', 'discord', 'matrix', 'mastodon', 'email', 'android']
  return names[id] || 'unknown'
}

export {
  discordToEnvelope,
  keetToDiscord,
  envelopeToDiscordContent,
  discordReactionToEnvelope
}