Youtube like4me bot
@lucasew
code:
data:privatelast updated:3 years ago
today
Build integrations remarkably fast!
You're viewing a public workflow template.
Sign up to customize, add steps, modify code and more.
Join 1,000,000+ developers using the Pipedream platform
steps.
trigger
HTTP API
Deploy to generate unique URL
This workflow runs on Pipedream's servers and is triggered by HTTP / Webhook requests.
steps.
nodejs
auth
to use OAuth tokens and API keys in code via theauths object
(auths.youtube_data_api)
(auths.telegram_bot_api)
params
Admid
 
string ·params.admid
code
Write any Node.jscodeand use anynpm package. You can alsoexport datafor use in later steps via return or this.key = 'value', pass input data to your code viaparams, and maintain state across executions with$checkpoint.
async (event, steps, params, auths) => {
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
const getIDFromYoutubeLink = require("pipedream-utils/lib/extractor/youtube/idFromUrl")
const getURLsFromString = require("pipedream-utils/lib/extractor/common/urlsFromString")
const segment = require("pipedream-utils/lib/list/segment")
if ($checkpoint === undefined) {
  $checkpoint = []
}
await $respond({
  status: 200,
  body: "ok"
})
let returnLines = []
const axios = require('axios').default
async function sendTelegram(text) {
  let promises = segment(text, 4096).map((payload) => new Promise(async (res, rej) => {
    while (true) {
      try {
        await axios({
          method: "post",
          url: `https://api.telegram.org/bot${auths.telegram_bot_api.token}/sendMessage`,
          data: {
            chat_id: params.admid,
            text: payload
          }
        }).then(res).finally(() => console.log("telegram request"))
        console.log("telegram: ok")
        return
      } catch(e) {
        console.log(e)
        console.log("request fail, retrying")
        setTimeout(() => {
          sendTelegram(`erro: ${e.message || e}`).then(res)
        }, 200)
      }
    }
  }))
  return Promise.all(promises)
}
async function handle() { 
  if (String(event.body.message.from.id) !== params.admid) {
    const j = JSON.stringify(event.body)
    console.log("não autorizado")
    returnLines.push(`Acesso não autorizado detectado: @${event.body.message.chat.username}\npayload: ${Buffer.from(j).toString("base64")}`)
    return
  }
  const allText = [
    event.body.message.caption,
    event.body.message.text
  ].map(String).join("\n")
  const ids = getURLsFromString(allText)
    .map(getIDFromYoutubeLink)
    .filter((item) => item.indexOf(".") === -1)
  $checkpoint = [...$checkpoint, ...ids]
  if (ids.length > 0) {
    returnLines.push("links encontrados")
  } else {
    returnLines.push("nenhum link novo foi encontrado")
  }
  console.log($checkpoint)

  if ($checkpoint.length > 0) {
    returnLines.push(`${$checkpoint.length} vídeos na fila para processar`)
    const requestedIds = $checkpoint
    $checkpoint = []
    const actions = requestedIds.map((id) => axios.post(
        `https://www.googleapis.com/youtube/v3/videos/rate?id=${id}&rating=like&access_token=${auths.youtube_data_api.oauth_access_token}`
      )
      .then(() => {
        returnLines.push(`youtu.be/${id} ok`)
      })
      .catch((e) => {
        returnLines.push(`youtu.be/${id} fail: ${e.message || e}`)
        console.log(e)
        $checkpoint.push(id)
      })
    )
    await Promise.all(actions)
  }
}
if (steps.trigger.raw_event.uri === "/telegram") {
  console.log("handle", await handle())
}
console.log(returnLines.join('\n'))
await sendTelegram(returnLines.join('\n'))