Telegram Alert bot stops with "WebException"

Created at 05 May 2020, 14:17
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
Gwave's avatar

Gwave

Joined 26.10.2014

Telegram Alert bot stops with "WebException"
05 May 2020, 14:17


Hi guys

I have this Telegram alert bot but everytime I start it, it crashes Onstart with "WebException" please help.

I have both the Channel ID and Key but nothing seems to work.

PS I am not a coder, so please if you could make the solutions relatively simple, I would greatly appreciate it. Many thanks

 

I have also changed the OnStart solution provide to the one below but still Crashes.

///////////

protected override void OnStart()
        {
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // If you didn't set a channel, then find channels by looking at the updates
            if (string.IsNullOrEmpty(ChannelId))
            {
                _telegramChannels = ParseChannels(GetBotUpdates());
            }
            else
            {
                _telegramChannels.Add(ChannelId);
            }
            SendMessageToAllChannels("Hellow world.. ");

        }

///////////

using System;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class TelegramBotExample : Robot
    {
        [Parameter("Telegram Bot Key", DefaultValue = "__bot_key__")]
        public string BOT_API_KEY { get; set; }

        // if you know which channel you want to broadcast to, add it here
        // otherwise the bot looks at the people and channels its' interacted with and
        // sends messages to everyone
        [Parameter("ChannelId", DefaultValue = "")]
        public string ChannelId { get; set; }


        List<string> _telegramChannels = new List<string>();

        protected override void OnStart()
        {
            // If you didn't set a channel, then find channels by looking at the updates
            if (string.IsNullOrEmpty(ChannelId))
            {
                _telegramChannels = ParseChannels(GetBotUpdates());
            }
            else
            {
                _telegramChannels.Add(ChannelId);
            }
            SendMessageToAllChannels("Hellow world.. ");

        }


        protected override void OnTick()
        {
            // Put your core logic here

        }

        protected override void OnBar()
        {
            // Put your core logic here
            int idx = this.MarketSeries.Close.Count - 2;
            if (this.MarketSeries.Close[idx] > this.MarketSeries.Open[idx])
            {
                SendMessageToAllChannels("Up Candle " + this.MarketSeries.Close[idx] + " " + this.MarketSeries.Open[idx]);
            }
            else
            {
                SendMessageToAllChannels("Down Candle " + this.MarketSeries.Close[idx] + " " + this.MarketSeries.Open[idx]);
            }
        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }


        //  Parses messages for bot and determines which channesl are listening
        private List<string> ParseChannels(string jsonData)
        {
            var matches = new Regex("\"id\"\\:(\\d+)").Matches(jsonData);
            List<string> channels = new List<string>();
            if (matches.Count > 0)
            {
                foreach (Match m in matches)
                {
                    if (!channels.Contains(m.Groups[1].Value))
                    {
                        channels.Add(m.Groups[1].Value);
                    }
                }
            }
            foreach (var v in channels)
            {
                Print("DEBUG: Found Channel {0} ", v);
            }
            return channels;
        }

        protected int updateOffset = -1;
        private string GetBotUpdates()
        {
            Dictionary<string, string> values = new Dictionary<string, string>();
            if (updateOffset > -1)
            {
                values.Add("offset", (updateOffset++).ToString());
            }

            var jsonData = MakeTelegramRequest(BOT_API_KEY, "getUpdates", values);

            var matches = new Regex("\"message_id\"\\:(\\d+)").Matches(jsonData);
            if (matches.Count > 0)
            {
                foreach (Match m in matches)
                {
                    int msg_id = -1;
                    int.TryParse(m.Groups[1].Value, out msg_id);
                    if (msg_id > updateOffset)
                    {
                        updateOffset = msg_id;
                    }
                }
            }
            return jsonData;
        }

        private void SendMessageToAllChannels(string message)
        {
            foreach (var c in _telegramChannels)
            {
                SendMessageToChannel(c, message);
            }
        }

        private string SendMessageToChannel(string chat_id, string message)
        {
            var values = new Dictionary<string, string> 
            {
                {
                    "chat_id",
                    chat_id
                },
                {
                    "text",
                    message
                }
            };

            return MakeTelegramRequest(BOT_API_KEY, "sendMessage", values);
        }

        private string MakeTelegramRequest(string api_key, string method, Dictionary<string, string> values)
        {
            string TELEGRAM_CALL_URI = string.Format("https://api.telegram.org/bot{0}/{1}", api_key, method);

            var request = WebRequest.Create(TELEGRAM_CALL_URI);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            StringBuilder data = new StringBuilder();
            foreach (var d in values)
            {
                data.Append(string.Format("{0}={1}&", d.Key, d.Value));
            }
            byte[] byteArray = Encoding.UTF8.GetBytes(data.ToString());
            request.ContentLength = byteArray.Length;

            Stream dataStream = request.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);

            dataStream.Close();

            WebResponse response = request.GetResponse();

            Print("DEBUG {0}", ((HttpWebResponse)response).StatusDescription);

            dataStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStream);

            string outStr = reader.ReadToEnd();

            Print("DEBUG {0}", outStr);

            reader.Close();

            return outStr;


        }
    }
}

@Gwave
Replies

ergun
12 May 2020, 21:06

RE:

Did you try to send a message to bot over telegram? Like sending a message to a person?


@ergun

Gwave
14 May 2020, 15:17

RE: RE:

ergun said:

Did you try to send a message to bot over telegram? Like sending a message to a person?

Hi ergun

Yes I did but it's not working at all.

Do you have any suggestions?

Any help would be much appreciated thanks.

Regards


@Gwave

Gwave
20 May 2020, 12:47

Hi Guys

Does anyone have any insight or solution to this?

Many thanks for all your help.

Regards

Gwave


@Gwave