ttezel / twit

Twitter API Client for node (REST & Streaming API)
4.31k stars 568 forks source link

Reply with images #407

Open vdivinity opened 6 years ago

vdivinity commented 6 years ago

How do I make it so that the bot replies with images / gifs?

renanmav commented 4 years ago

I’ve created this function to do this.

interface SendReplyWithMediaArgs {
  filePath: string
  profileName: string
  message: string
  statusId: string
}

export function sendReplyWithMedia(
  twit: Twit,
  { filePath, profileName, message, statusId }: SendReplyWithMediaArgs,
  isProd: boolean,
) {
  twit.postMediaChunked(
    {
      file_path: filePath,
    },
    (_, data) => {
      const { media_id_string: mediaId } = data as PostMediaChunkedResponse
      const params = {
        status: `@${profileName} ${message}`,
        media_ids: [mediaId],
        in_reply_to_status_id: statusId,
      }
      twit.post('statuses/update', params, (err, result) => {
        if (err || !result)
          throw new Error(
            `Error creating reply to https://twitter.com/${profileName}/${statusId}` +
              !isProd &&
              `\n\nerr: ${JSON.stringify(err)}` +
                `\n\nresult: ${JSON.stringify(result)}`,
          )
      })
    },
  )
}