N8N Telegram Perplexity

Overview

Eventually, while looking for a solution to improve my note taking activities, I realized that one of my requirements was to easily capture thoughts that were popping in my head, and persist it somewhere. While looking for a solution, I found out an integration between Telegram, a workflow managing application, some AI to start researches and Obsidian. Unfortunately I gave up Obsidian, but this iflow was very interesting to me. So I decided to use Telegram to trigger a search on Perplexity.AI, and persist the result to my Gitea repository for future analysis and processing. One more step is to add an entry in my ToDo App, or through Google Calendar, to not forget about it. As I use Joplin for my note taking apps, I dont have a way to push notes automatically to it. At least I havent figure it out yet. It s not really an issue, as I want to digest the information gathered by Perplexity first.

Telegram Integration

Telegram is available on multiple platform : * Android * Windows * Linux * Apple ecosystem, but I do not need it It is also free.

Once registered as a normal user to Telegram, open a chat and start a chat with @botfather. In the chat, type /start to get a list of all possible commands. To create your own bot, enter /newbot. After selecting a name for the bot, with _bot suffix, the bot will be created and a token will be provided to connect to that bot. Keep this token somewhere safe and do not share it with anyone. It will be used in n8n to connect to the bot.

Now in n8n, on the main page, click on the Create button and select Credentials. Create Credentials

Next, start typing Telegram, until you can choose Telegram API. Create Credentials - Select Telegram

And now you can change the name of the account by overing over it and clickin gon the edit button. Paste the Token API Key bellow the Access Key label. Telegram Credentials

Once the credentials are saved, on the main page create a new workflow by clicking one the Create button and select Workflow. Click on the shape in the middle and select On App Event in the menu that pops. Trigger Selection

Then, select the Telegram application and the On Message entry : Telegram Trigger

Next, we have to configure the shape we have just created. In the property window, select the Telegram account created earlier, and set the Trigger On to Message.

Configure Telegram Trigger

Now it is possible to start testing the workflow. Pressing the Test Step button, the workflow will be waiting for a signal from Telegram. In Telegram, sent a message to the bot the workflow will be triggered automatically and the payload received will be shown in the right pane: Telegram Output

Filter Bot commands

As described in the Telegram bot documentation, the bot should answet to specific commands, like /new, /start, … So I will use a switch component to check for those commands before triggering anything. I want to query Perplexity.ai only when the message is starting with the command /check. To do this close the previous page by clicking on Back to canvas link in the top left part of the panel. Next click on the + sign on the top right of the canvas and select the switch component. Select Switch

Next, Get back to the canvas, and link the Telegram shape to the newly created shape. This will allow the applicaiton to show the content of the payload in the shape configuration. Switch Configuration Now that we can see the initial payload, drag and drop the Text node to the Value 1 field, then in the field next to it, select the string function start with . For this example, I have set the expected value to This to have a positive test, and I am pressing on the Test Step button, the payload should appear on the right. This shows this is working properly. To fit this to what I want to achieve, I will replace the value This from my message to /check. When I am testing again, the payload disappear on the right.

For the following examples, I will use the message /check What are the planets in our Solar system, starting by the closest planet from the sun. Had a description of the planet..

Perplexity Integration

Perplexity.AI is is an AI-powered research assistant that helps users find relevant information on the web. It’s a search engine that uses natural language processing (NLP) to understand the context of a search query and provide more accurate results. When using the web interface it keeps track of all the requests. One interesting aspect of that tool is that it will provide links to scientific ressources.

To integrate with the API, it s required to register with a credit card and add some credit on the account. Limiting the calls to 1,000 tokens, each query cost me 0.01$ so far. The API key generated in the application is accessible through the settings, in the API section.

Before sending my request to Perplexity.ai, I need to clean up the message and remove the /check command. To do this I will add a Set shape. To remove the command from the string I will use the following javascript code :

1
{{ $json.message.text.split(' ').slice(1).join(' ') }}

This is how the shape configuration should look like : Clean Request So on the left we have the payload received from Telegram and the history, for each shape we can see the status of the payload. This allow us to retrieve initial values when required. In the middle, we find how the output fields are being constructed. There can be more fields if we need. On the right is the resul payload. We can see the initial message without the /check command.

Next, we go back to the canvas, then add a Web Request shape, and open the configuration of the shape. We will use the Import cURL on the top right to configure this shape easily. To Do this, lets go to Perplexity.ai API documentation . There we can find the cURL command to query the API. Simply copy paste it to n8n. Now that the fields I filled in, let’s update the content with the dynamic data.

In the Headers section, the Authorization value field should be updated with the API token provided in Perplexity.ai (Bearer <token>) Next in the Json part, we should use expression and update some content fields : "content": "{{ $json.message.text.replace(/\n/g, ' ') }}". (There should be no newlines in the payloads !)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  "messages": [
    {
      "role": "system",
      "content": "Be precise and concise. Summarize the results and provides 
      links to the sources, with a weight in percentage showing what are the 
      most interesting results."
    },
    {
      "role": "user",
      "content": "{{ $json.message.text.replace(/\n/g, '') }}"
    }
  ],

Update "max_tokens": "1024",

Pressing the Test Step button should query the API and return some results. Troubleshoot errors if required. Here is the results I had :

 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
[
  {
    "id": "f853e1f6-cfad-402a-aa20-7e04c7c9adb5",
    "model": "llama-3.1-sonar-small-128k-online",
    "created": 1735849634,
    "usage": {
      "prompt_tokens": 55,
      "completion_tokens": 631,
      "total_tokens": 686
    },
    "citations": [
      "https://www.sciencefocus.com/space/planets-in-order-solar-system",
      "https://www.space.com/16080-solar-system-planets.html",
      "https://www.youtube.com/watch?v=oHahGWzLpl0",
      "https://science.nasa.gov/solar-system/planet-sizes-and-locations-in-our-solar-system/",
      "https://www.skyatnightmagazine.com/space-science/planets-solar-system-guide"
    ],
    "object": "chat.completion",
    "choices": [
      {
        "index": 0,
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "The planets in our Solar System, starting from the closest to the Sun, are:\n\n
          1. **Mercury**:\n   - **Distance from Sun**: 0.39 AU\n   - **Diameter**: 3,457 km\n   
          - **Surface Temperature**: -180 °C to 430 °C (average 167 °C)\n   - **Gravity**: About 38% of 
          Earth's gravity\n   - **Orbit**: Egg-shaped, closest to Earth on average[1][2][5].\n\n2. 
          **Venus**:\n   - **Distance from Sun**: 0.72 AU\n   - **Diameter**: 12,104 km\n   - **Surface 
          Temperature**: Extremely hot, around 462 °C (863 °F)\n   - **Atmosphere**: Thick atmosphere 
          composed mainly of carbon dioxide[1][2][5].\n\n3. **Earth**:\n   - **Distance from Sun**: 1 AU\n
           - **Diameter**: 12,756 km\n   - **Surface Temperature**: Varies from -89 °C to 57 °C\n
           - **Atmosphere**: Nitrogen, oxygen, and other gases[1][2][5].\n\n4. **Mars**:\n
           - **Distance from Sun**: 1.5 AU\n   - **Diameter**: 6,792 km\n   - **Surface Temperature**: 
           -125 °C to 20 °C\n   - **Atmosphere**: Thin atmosphere with mostly carbon dioxide[1][2][5].\n\n
           5. **Jupiter**:\n   - **Distance from Sun**: 5.2 AU\n   - **Diameter**: 142,984 km\n   
           - **Moons**: 79 (including Ganymede, the largest moon in the Solar System)\n   - **Atmosphere**:
           Composed of hydrogen and helium, with swirling clouds of ammonia ice and water vapor[2][5].\n\n6. 
           **Saturn**:\n   - **Distance from Sun**: 9.54 AU\n   - **Diameter**: 120,536 km\n   - **Moons**: 
           82 (including Titan, the second-largest moon in the Solar System)\n   - **Ring System**: 
           Distinct and extensive ring system[2][5].\n\n7. **Uranus**:\n   - **Distance from Sun**: 19.2 
           AU\n   - **Diameter**: 51,118 km\n   - **Moons**: 27\n   - **Atmosphere**: Composed mainly of 
           hydrogen, helium, and methane, which gives it a blue color[1][2][5].\n\n8. **Neptune**:\n   
           - **Distance from Sun**: 30 AU\n   - **Diameter**: 49,528 km\n   - **Moons**: 14\n   
           - **Atmosphere**: Composed mainly of hydrogen and helium, with strong winds and storm 
           systems[1][2][5].\n\nThese descriptions provide a comprehensive overview of each planet in our 
           Solar System, starting from the closest to the Sun."
        },
        "delta": {
          "role": "assistant",
          "content": ""
        }
      }
    ]
  }
]

It is possible to change the model used to do the query, but pay attention that the pricing is changing according to the model used.

    "model": "llama-3.1-sonar-small-128k-online"

Possible models are :

  • llama-3.1-sonar-small-128k-online
  • llama-3.1-sonar-large-128k-online
  • llama-3.1-sonar-huge-128k-online

Here is the result for the Large model :

 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
[
  {
    "id": "c4196fc5-e6aa-493c-8fe6-6536140d7024",
    "model": "llama-3.1-sonar-large-128k-online",
    "created": 1735851774,
    "usage": {
      "prompt_tokens": 55,
      "completion_tokens": 1024,
      "total_tokens": 1079
    },
    "citations": [
      "https://www.sciencefocus.com/space/planets-in-order-solar-system",
      "https://www.galactic-hunter.com/post/planets-in-order",
      "https://www.youtube.com/watch?v=oHahGWzLpl0",
      "https://science.nasa.gov/solar-system/planet-sizes-and-locations-in-our-solar-system/",
      "https://www.space.com/16080-solar-system-planets.html"
    ],
    "object": "chat.completion",
    "choices": [
      {
        "index": 0,
        "finish_reason": "length",
        "message": {
          "role": "assistant",
          "content": "Here are the planets in our Solar System, listed in order from closest to 
          farthest from the Sun, along with a brief description of each:\n\n## Mercury\n- 
          **Distance from Sun:** 36 million miles (58 million kilometers)[4].\n- **Diameter:** 
          3,032 miles (4,880 kilometers)[4].\n- **Type:** Terrestrial planet.\n- **Temperature:** 
          -173°C to 427°C (-279°F to 801°F)[2].\n- **Orbit:** 88 Earth days; day: 59 Earth days
          [2].\n- **Moons:** None.\n- **Description:** Mercury is the smallest planet and the 
          closest to the Sun. It has a highly elliptical orbit and a very thin atmosphere[1][2][4].
          \n\n## Venus\n- **Distance from Sun:** 67.2 million miles (108 million kilometers)[4].\n
          - **Diameter:** 12,104 kilometers (7,521 miles)[1].\n- **Type:** Terrestrial planet.\n
          - **Temperature:** Surface temperature is around 462°C (863°F) due to a thick atmosphere[1].\n
          - **Orbit:** 225 Earth days; day: 243 Earth days[2].\n- **Moons:** None.\n- **Description:** 
          Venus is known for its dense atmosphere, which makes it the hottest planet in the Solar 
          System[1][2][4].\n\n## Earth\n- **Distance from Sun:** 93 million miles (149.7 million 
          kilometers)[4].\n- **Diameter:** 12,756 kilometers (7,926 miles)[1].\n- **Type:** Terrestrial 
          planet.\n- **Temperature:** Average surface temperature is around 15°C (59°F)[1].\n
          - **Orbit:** 365.25 Earth days; day: 24 hours.\n- **Moons:** One (the Moon).\n
          - **Description:** Earth is the third planet from the Sun and the only known planet to 
          support life. It has a diverse range of environments and a moderate atmosphere[1][2][4].\n\n
          ## Mars\n- **Distance from Sun:** 141.6 million miles (227.9 million kilometers)[4].\n
          - **Diameter:** 6,792 kilometers (4,220 miles)[1].\n- **Type:** Terrestrial planet.\n
          - **Temperature:** Average temperature is around -67°C (-89°F)[4].\n- **Orbit:** 687 Earth days; 
          day: 24.6 hours[2].\n- **Moons:** Two (Phobos and Deimos).\n- **Description:** Mars, known 
          as the Red Planet, has a rocky surface and is a potential candidate for supporting life. 
          It has the tallest volcano in the Solar System, Olympus Mons[1][2][4].\n\n## Jupiter\n
          - **Distance from Sun:** 483.7 million miles (778 million kilometers)[4].\n- **Diameter:** 
          142,984 kilometers (88,846 miles)[1].\n- **Type:** Gas giant.\n- **Temperature:** Cloud tops 
          are around -150°C (-238°F)[5].\n- **Orbit:** 11.9 Earth years; day: 9.8 hours[5].\n- **Moons:** 
          79 known moons, including Ganymede, the largest moon in the Solar System[5].\n
          - **Description:** Jupiter is the largest planet in the Solar System, known for its massive 
          size, strong magnetic field, and the Great Red Spot, a giant storm[1][2][5].\n\n## Saturn\n
          - **Distance from Sun:** 889.8 million miles (1.4 billion kilometers)[4].\n- **Diameter:** 
          120,536 kilometers (74,900 miles)[1].\n- **Type:** Gas giant.\n- **Temperature:** Cloud tops 
          are around -178°C (-280°F)[5].\n- **Orbit:** 29.5 Earth years; day: 10.5 hours[5].\n
          - **Moons:** 82 known moons[5].\n- **Description:** Saturn is famous for its extensive ring 
          system and has a lower density than water. It is known for its moons, including Titan and 
          Enceladus[1][2][5].\n\n## Uranus\n- **Distance from Sun:** 1.8 billion miles (2.9 billion 
          kilometers)[4].\n- **Diameter:** 51,118 kilometers (31,763 miles)[1].\n- **Type:** 
          Ice giant.\n- **Temperature:** Cloud tops are around -216°C (-360°F)[4].\n- **Orbit:** 84 
          Earth years; day: 17.9 hours[4].\n- **Moons:** 27 known moons[4].\n- **Description:** Uranus 
          is the seventh planet from the Sun and is known for its tilted axis, which results in extreme 
          seasons. It has a thin atmosphere and a system of rings and moons[1][2][4].\n\n## Neptune\n
          - **Distance from Sun:** 2.8 billion miles (4.5 billion kilometers)[4].\n- **"
        },
        "delta": {
          "role": "assistant",
          "content": ""
        }
      }
    ]
  }
]

Sending Result to Telegram

Back to the canvaqs, add a Telegram shape of type Send Message. To configure, you can drag and drop the fields from the left panel, then edit the code generated with the specific functions used. First we need to send the response to the proper chat, filling in the Chat ID with the value from the initial request : {{ $('Telegram Trigger').item.json.message.from.id }}. Next in the Text field, we just have to format the output message that we went to send back to the user. In my case this is what is sent :

{{ $json.choices[0].message.content }}
References : 
{{ $json.citations.join('\n') }}

Telegram Send Response And that is it for the user.

Gitea Integration

Within Gitea, create a new repository that will receive all the request results. Create a new API access token and keep it safe someplace (I use KeePass to save the credentials as once you close the page from gitea, you will no longer have access to the key, you will have to create a new one.)

Back on n8n, add a new http request to send the payload to Gitea. But before creating the request, we need to generate the markdown payload and transform it into base64. To achieve this, we need to add 2 new Set shapes and link the shape as follow : Gitea Send Shapes

To generate the markdown content, here is how I configure the shape : Gitea Send Shapes (“output” should not contain any new lines.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{ 
  "when" : "{{ $now.format('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\'') }}",
  "filename" : "{{ 'AI-Bot-Req-' + $now.format('yyyyMMddHHmmss') }}",
  "output": "## Request\n{{ $('Route Command').item.json.message.text.replace(/\n/g, '\\n') }}
  \n\n ## Response\n{{ $json.choices[0].message.content.replace(/\n/g, '\\n') }}\n\n## References
  \n{{ $json.citations.join('\\n') }}\n\n## Statistics\nPrompt Tokens \t: 
  {{ $json.usage.prompt_tokens }}\nCompletion Tokens \t: {{ $json.usage.completion_tokens }}\n
  Total Tokens \t: {{ $json.usage.total_tokens }}\nRequested By : 
  {{ $('Telegram Trigger').item.json.message.from.last_name }} 
  {{ $('Telegram Trigger').item.json.message.chat.first_name }}",
  "encoded": ""
}

In the next shape, we will transform the payload into base64 encoding. Gitea Send Shapes

1
2
3
4
5
{
  "when": "{{ $json.when }}",
  "filename": "{{ $json.filename }}",
  "encoded": "{{ $json.output.base64Encode() }}"
}

The http request is creating the payload to create a new file into a gitea repository. The Header Authorization must contain the API token created in Gitea. Gitea Send Shapes

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
{
  "author": {
    "email": "[email protected]",
    "name": "username"
  },
  "branch": "main",
  "committer": {
    "email": "[email protected]",
    "name": "username"
  },
  "content": "{{ $json.encoded }}",
  "dates": {
    "author": "{{ $json.when }}",
    "committer": "{{ $json.when }}"
  },
  "message": "AI-Bot response from query {{ $json.filename }}",
  "signoff": true
}

Once Test is complete, the result is in Gitea : Gitea Send Shapes

References