Example #1
0
        private void Bot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            string chatidmovaqat = e.Message.Chat.Id.ToString();

            try {
                if (e.Message.Type == Telegram.Bot.Types.Enums.MessageType.AudioMessage)
                {
                    bot.SendChatActionAsync(chatidmovaqat, Telegram.Bot.Types.Enums.ChatAction.FindLocation);
                    string FileName  = e.Message.Audio.Title.ToString();
                    string Duration  = e.Message.Audio.Duration.ToString();
                    string performer = e.Message.Audio.Performer.ToString();
                    if (FileName.Length > 50 || FileName.Contains("@") || FileName.Contains("_") || FileName.Contains("%") || FileName.Contains("#") || e.Message.Audio.Performer == null || e.Message.Audio.Performer.Length > 50 || e.Message.Audio.Performer.Contains("@") || e.Message.Audio.Performer.Contains("[") || e.Message.Audio.Performer.Contains("{") || e.Message.Audio.Performer.ToLower().Contains(".com") || e.Message.Audio.Performer.ToLower().Contains(".ir") || e.Message.Audio.Performer.ToLower().Contains("www") || e.Message.Audio.Title.ToLower().Contains("www") || e.Message.Audio.Title.ToLower().Contains("remix") || e.Message.Audio.Title.ToLower().Contains("hha"))
                    {
                        bot.SendTextMessageAsync(chatidmovaqat, "مطابق معیارای استاد نیست.", 0, false, true, e.Message.MessageId);
                    }
                    else
                    {
                        Class1 myclass = new Class1();
                        if (myclass.checkdublicate(FileName, performer) == false)
                        {
                            SqlConnection myconnection = new SqlConnection();
                            myconnection.ConnectionString = connection;
                            SqlCommand mycommand = new SqlCommand();
                            mycommand.Connection  = myconnection;
                            mycommand.CommandText = "insert into[melo] (fileid,filename,performer,path,duration,size) values(@fileid,@filename,@performer,@path,@duration,@size)";    //sets info
                            mycommand.Parameters.AddWithValue("@fileid", e.Message.Audio.FileId.ToString());
                            mycommand.Parameters.AddWithValue("@filename", e.Message.Audio.Title.ToString());
                            mycommand.Parameters.AddWithValue("@performer", e.Message.Audio.Performer.ToString());
                            if (e.Message.Audio.FilePath != null)
                            {
                                mycommand.Parameters.AddWithValue("@path", e.Message.Audio.FilePath.ToString());
                            }
                            else
                            {
                                mycommand.Parameters.AddWithValue("@path", "0");
                            }
                            mycommand.Parameters.AddWithValue("@duration", e.Message.Audio.Duration.ToString());
                            mycommand.Parameters.AddWithValue("@size", e.Message.Audio.FileSize.ToString());
                            myconnection.Open();
                            mycommand.ExecuteNonQuery();
                            myconnection.Close();
                            bot.SendTextMessageAsync(chatidmovaqat, "ثبت شد.");
                        }
                        else
                        {
                            bot.SendTextMessageAsync(chatidmovaqat, "تکراری بود", 0, false, false, e.Message.MessageId);
                        }
                    }
                }
                else if (e.Message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                {
                    if (e.Message.Text.Length > 50 && !e.Message.Text.Contains("\U0001F464") && !e.Message.Text.Contains("\U0001F3B5"))
                    {
                        bot.SendTextMessageAsync(chatidmovaqat, "Stop spamming \U0001F620 ");
                    }
                    else
                    {
                        if (e.Message.Text.ToLower() == "count bitch")
                        {
                            int           count        = 0;
                            SqlConnection myconnection = new SqlConnection();
                            myconnection.ConnectionString = connection;
                            SqlCommand mycommand = new SqlCommand();
                            mycommand.Connection  = myconnection;
                            mycommand.CommandText = "select count(*) from [melo] ";
                            myconnection.Open();
                            try
                            {
                                count = (Int32)mycommand.ExecuteScalar();
                                myconnection.Close();
                                bot.SendTextMessageAsync(chatidmovaqat, count.ToString() + " U fCkIn IdIot :/", Telegram.Bot.Types.Enums.ParseMode.Html);
                            }
                            catch { }
                            myconnection.Close();
                        }
                        else if (e.Message.Text.ToLower() == "/today")
                        {
                            int           count        = 0;
                            SqlConnection myconnection = new SqlConnection();
                            myconnection.ConnectionString = connection;
                            SqlCommand mycommand = new SqlCommand();
                            mycommand.Connection  = myconnection;
                            mycommand.CommandText = "SELECT COUNT(*) FROM   [meloii] where [tarix]=@date";
                            mycommand.Parameters.AddWithValue("@date", DateTime.Today.ToShortDateString());
                            myconnection.Open();
                            count = (Int32)mycommand.ExecuteScalar();
                            myconnection.Close();
                            bot.SendTextMessageAsync(chatidmovaqat, count.ToString() + " U fCkIn IdIot :/");
                            myconnection.Close();
                        }
                        else
                        {
                            string text = e.Message.Text;
                            try
                            {
                                SqlConnection myconnection = new SqlConnection();
                                myconnection.ConnectionString = connection;
                                SqlCommand mycommand = new SqlCommand();
                                mycommand.Connection = myconnection;
                                DataTable      mytable   = new DataTable();
                                SqlDataAdapter myadapter = new SqlDataAdapter();
                                Class1         myclass   = new Class1();
                                if (myclass.PerformerCheck(text, 30) && !text.Contains("\U0001F464")) // sheklake Person ro nadarad.
                                {
                                    string textORG = text;
                                    for (int i = 0; i < text.Length + 1; i = i + 2)
                                    {
                                        text = text.Insert(i, "%");
                                    }
                                    text = text.Replace("'", "''");
                                    mycommand.CommandText = "select performer from [melo] where [performer] like '" + text + "' order by performer";

                                    myconnection.Open();
                                    myadapter.SelectCommand = mycommand;
                                    myadapter.Fill(mytable);
                                    myconnection.Close();
                                    List <string> performers = new List <string>();
                                    List <string> filename   = new List <string>();
                                    foreach (DataRow duck in mytable.Rows)
                                    {
                                        if (myclass.CalculateSimilarity(duck["performer"].ToString(), textORG) > 30)
                                        {
                                            if (performers.Count == 0)
                                            {
                                                performers.Add(duck["performer"].ToString());
                                                filename.Add("");
                                            }

                                            else if (myclass.CalculateSimilarity(performers.Last().ToLower(), duck["performer"].ToString().ToLower()) < 70)
                                            {
                                                performers.Add(duck["performer"].ToString());
                                                filename.Add("");
                                            }
                                        }
                                    }
                                    // adding some songs here :/

                                    SqlConnection myconnection1 = new SqlConnection();
                                    myconnection1.ConnectionString = connection;
                                    SqlCommand mycommand1 = new SqlCommand();
                                    mycommand1.Connection = myconnection1;
                                    DataTable      mytable1   = new DataTable();
                                    SqlDataAdapter myadapter1 = new SqlDataAdapter();
                                    mycommand1.CommandText = "select performer,filename from [melo] where [filename] like '%" + textORG + "%' order by rate DESC";
                                    myconnection1.Open();
                                    myadapter1.SelectCommand = mycommand1;
                                    myadapter1.Fill(mytable1);
                                    myconnection1.Close();
                                    foreach (DataRow duck in mytable1.Rows)
                                    {
                                        performers.Add(duck["performer"].ToString());
                                        filename.Add(duck["filename"].ToString());
                                        if (performers.Count > 100)
                                        {
                                            break;
                                        }
                                    }
                                    bot.SendTextMessageAsync(chatidmovaqat, performers.LongCount().ToString() + "مورد مشابه یافت شد", 0, false, false, 0, Class1.ButtonCreatorObjecti(filename, performers));
                                }


                                else if (text.Contains("\U0001F464") && !text.Contains("\U0001F3B5")) //sheklake adamako darad vali MELODI na
                                {
                                    text = text.Replace("\U0001F464", "");
                                    text = text.Replace("'", "''");
                                    if (text.Contains(" "))
                                    {
                                        if (text.IndexOf(" ") == 0 || text.LastIndexOf(" ") == text.Length - 1)
                                        {
                                            text = text.Replace(" ", "");
                                        }
                                    }
                                    string textORG = text;
                                    for (int i = 0; i < text.Length + 1; i = i + 2)
                                    {
                                        text = text.Insert(i, "%");
                                    }
                                    mycommand.CommandText = "select filename,performer from [melo] where [performer] like '" + text + "' order by performer";
                                    myconnection.Open();
                                    myadapter.SelectCommand = mycommand;
                                    myadapter.Fill(mytable);
                                    myconnection.Close();
                                    List <string> performers = new List <string>();
                                    List <string> filename   = new List <string>();

                                    foreach (DataRow duck in mytable.Rows)
                                    {
                                        if (performers.Count == 0)
                                        {
                                            performers.Add(duck["performer"].ToString());
                                            filename.Add(duck["filename"].ToString());
                                        }
                                        else if (((performers.Last() != duck["performer"].ToString() || filename.Last() != duck["filename"].ToString()) && (myclass.CalculateSimilarity(textORG, duck["performer"].ToString()) > 50)) || duck["performer"].ToString().ToLower() == textORG.ToLower())
                                        {
                                            performers.Add(duck["performer"].ToString());
                                            filename.Add(duck["filename"].ToString());
                                        }

                                        if (performers.Count > 70)
                                        {
                                            break;
                                        }
                                    }

                                    bot.SendTextMessageAsync(chatidmovaqat, "از میان این گزینه ها انتخاب کنید:", 0, false, false, 0, Class1.ButtonCreatorObjecti(filename, performers));
                                }
                                else if (text.Contains("\U0001F3B5") && text.Contains("\U0001F464")) //	musical note darad + adamak
                                {
                                    string Fname     = text.Substring(text.IndexOf("\U0001F3B5"), text.IndexOf("\U0001F464"));
                                    string Performer = text.Substring(text.IndexOf("\U0001F464"));
                                    mycommand.CommandText = "select fileid,rate from [melo] where [filename]=@name and [performer]=@perf";
                                    mycommand.Parameters.AddWithValue("@name", Fname);
                                    mycommand.Parameters.AddWithValue("@perf", Performer);
                                    myconnection.Open();
                                    myadapter.SelectCommand = mycommand;
                                    myadapter.Fill(mytable);
                                    myconnection.Close();
                                    string id  = "";
                                    int    sum = 0;
                                    foreach (DataRow duck in mytable.Rows)
                                    {
                                        id  = duck["fileid"].ToString();
                                        sum = Convert.ToInt32(duck["rate"]);
                                        //bot.SendAudioAsync(chatidmovaqat, new FileToSend(duck["fileid"].ToString()), "\U0001F916" + "\U0001F194" + ":" + "@WeSongbot", 100, "", "");
                                        bot.SendAudioAsync(chatidmovaqat, new Telegram.Bot.Types.FileToSend(id), "\U0001F916 : @Testonybot \n", 100, "", "");
                                    }
                                    myclass.NewRate(id, sum);
                                    myclass.UpdateLastUse(chatidmovaqat);
                                }


                                else if (!e.Message.Text.Contains("\U0001F50D")) //magnifyer nadare    //age chizi k mixad jozve performera nist inja search ishe(searche asli)
                                {
                                    string text1 = e.Message.Text.Replace("'", "''");
                                    text1 = text1.Replace(" ", "%");
                                    mycommand.CommandText   = "select fileid,duration,performer,filename from [melo] where [filename] like '%" + text1 + "%'" + " or [performer] like '%" + text1 + "%'";
                                    myadapter.SelectCommand = mycommand;
                                    myconnection.Open();
                                    myadapter.Fill(mytable);
                                    myconnection.Close();
                                    int count = mytable.Rows.Count;
                                    if (count == 0)
                                    {
                                        string[] tokens = text.ToLower().Split(' ');

                                        SqlConnection myconnection10 = new SqlConnection();
                                        myconnection10.ConnectionString = connection;
                                        SqlCommand mycommand10 = new SqlCommand();
                                        mycommand10.Connection = myconnection10;
                                        DataTable      mytable10   = new DataTable();
                                        SqlDataAdapter myadapter10 = new SqlDataAdapter();
                                        mycommand10.CommandText = "select filename,performer from [melo] ";
                                        myconnection10.Open();
                                        myadapter10.SelectCommand = mycommand10;
                                        myadapter10.Fill(mytable10);
                                        myconnection10.Close();
                                        List <int> listmoqayese  = new List <int>();
                                        List <int> listmoqayese2 = new List <int>();
                                        var        list          = new List <Data>();

                                        Dictionary <string, int> result = new Dictionary <string, int>();
                                        foreach (DataRow duk in mytable10.Rows)
                                        {
                                            string   title      = duk["filename"].ToString().ToLower();
                                            string   raqqas     = duk["performer"].ToString().ToLower();
                                            string   bounded    = title + " " + raqqas;
                                            string[] boundedArr = bounded.Split(' ');
                                            foreach (string S in tokens)
                                            {
                                                foreach (string p in boundedArr)
                                                {
                                                    listmoqayese.Add(myclass.CalculateSimilarity(S, p));
                                                }

                                                listmoqayese2.Add(listmoqayese.Max());
                                                listmoqayese.Clear();
                                            }
                                            if (Convert.ToInt32(listmoqayese2.Average()) < 20)
                                            {
                                                continue;
                                            }
                                            int av = Convert.ToInt32(listmoqayese2.Average());
                                            list.Add(new Data("\U0001F3B5" + duk["filename"].ToString() + "\U0001F464" + duk["performer"].ToString(), av));
                                            listmoqayese2.Clear();
                                        }
                                        list.OrderBy(pair => pair.Value);
                                        var result1 = from pair in list orderby pair.Value descending select pair;

                                        result1.ToList();
                                        ////resultend = list.ToDictionary<KeyValuePair<string, int>, string, int>(pair => pair.Key, pair => pair.Value);
                                        //for(int i=0; i < 70; i++)
                                        //{
                                        //    resultend.Add(list.ElementAt(i).ToString(), i);

                                        //}
                                        bot.SendTextMessageAsync(chatidmovaqat, " مواردی که ممکنه مطابق نباشه:", 0, false, false, 0, Class1.ButtonOBJEee(result1.ToList()));
                                    }

                                    #region bullshits

                                    //////////////////    else
                                    //////////////////    {
                                    //////////////////        bot.SendTextMessageAsync(chatidmovaqat, "مورد مشابهی ندیدم :( میشه اگه پیدا کردی به منم بفرستیش؟");
                                    //////////////////    }
                                    //////////////////}



                                    //if (myclass.PerformerCheck(tokens[0], 80))
                                    //{

                                    //    //SqlConnection myconnection10 = new SqlConnection();
                                    //    //myconnection10.ConnectionString = connection;
                                    //    //SqlCommand mycommand10 = new SqlCommand();
                                    //    //mycommand10.Connection = myconnection10;
                                    //    //DataTable mytable10 = new DataTable();
                                    //    //SqlDataAdapter myadapter10 = new SqlDataAdapter();
                                    //    mycommand10.CommandText = "select filename,performer from [melo] where [performer] like'%" + tokens[0] + "%'";
                                    //    myconnection10.Open();
                                    //    myadapter10.SelectCommand = mycommand10;
                                    //    myadapter10.Fill(mytable10);
                                    //    myconnection10.Close();


                                    //    Dictionary<string, int> resultend = new Dictionary<string, int>();
                                    //    foreach (DataRow duk in mytable10.Rows)
                                    //    {
                                    //        string performerEND = duk["performer"].ToString();
                                    //        string title = duk["filename"].ToString();
                                    //        string retVal = text.Replace(tokens[0], "");
                                    //        int calc = myclass.CalculateSimilarity(title, retVal);

                                    //        result.Add("\U0001F3B5" + title + "\U0001F464" + performerEND,calc);

                                    //        if (result.Count > 70) break;
                                    //    }
                                    //    var result1 = from pair in result orderby pair.Value descending select pair;

                                    //    foreach(KeyValuePair<string,int> pair in result1)
                                    //    {
                                    //        resultend.Add(pair.Key, pair.Value);
                                    //    }



                                    //else if (myclass.PerformerCheck(tokens[1],80))
                                    //{

                                    //    SqlConnection myconnection10 = new SqlConnection();
                                    //    myconnection10.ConnectionString = connection;
                                    //    SqlCommand mycommand10 = new SqlCommand();
                                    //    mycommand10.Connection = myconnection10;
                                    //    DataTable mytable10 = new DataTable();
                                    //    SqlDataAdapter myadapter10 = new SqlDataAdapter();
                                    //    mycommand10.CommandText = "select filename,performer from [melo] where [filename] like '%" + tokens[0] + "%'" + "and [performer] ='" + tokens[1] + "'";
                                    //    myconnection10.Open();
                                    //    myadapter10.SelectCommand = mycommand10;
                                    //    myadapter10.Fill(mytable10);
                                    //    myconnection10.Close();

                                    //    List<string> result = new List<string>();
                                    //    foreach (DataRow duk in mytable10.Rows)
                                    //    {
                                    //        string performerEND = duk["performer"].ToString();
                                    //        string title = duk["filename"].ToString();
                                    //        result.Add("\U0001F3B5" + title + "\U0001F464" + performerEND);
                                    //        if (result.Count > 70) break;
                                    //    }
                                    //    bot.SendTextMessageAsync(chatidmovaqat, mytable10.Rows.Count.ToString() + "مورد خاص یافت شد که ممکنه مطابق نباشه:", 0, false, false, 0, Class1.ButtonOBJEee(result));

                                    //}

                                    //else if (myclass.PerformerCheck(tokens.Last(), 80))
                                    //{

                                    //    //SqlConnection myconnection10 = new SqlConnection();
                                    //    //myconnection10.ConnectionString = connection;
                                    //    //SqlCommand mycommand10 = new SqlCommand();
                                    //    //mycommand10.Connection = myconnection10;
                                    //    //DataTable mytable10 = new DataTable();
                                    //    //SqlDataAdapter myadapter10 = new SqlDataAdapter();
                                    //    mycommand10.CommandText = "select filename,performer from [melo] where [performer] like'%" + tokens.Last() + "%'";
                                    //    myconnection10.Open();
                                    //    myadapter10.SelectCommand = mycommand10;
                                    //    myadapter10.Fill(mytable10);
                                    //    myconnection10.Close();

                                    //    Dictionary<string, int> result = new Dictionary<string, int>();
                                    //    Dictionary<string, int> resultend = new Dictionary<string, int>();
                                    //    foreach (DataRow duk in mytable10.Rows)
                                    //    {
                                    //        string performerEND = duk["performer"].ToString();
                                    //        string title = duk["filename"].ToString();
                                    //        string retVal = text.Replace(tokens.Last(), "");
                                    //        int calc = myclass.CalculateSimilarity(title, retVal);
                                    //        result.Add("\U0001F3B5" + title + "\U0001F464" + performerEND, calc);
                                    //        if (result.Count > 70) break;
                                    //    }
                                    //    var result1 = from pair in result orderby pair.Value descending select pair;
                                    //    foreach (KeyValuePair<string, int> pair in result1)
                                    //    {
                                    //        resultend.Add(pair.Key, pair.Value);
                                    //    }
                                    //    bot.SendTextMessageAsync(chatidmovaqat, mytable10.Rows.Count.ToString() + "مورد خاص یافت شد که ممکنه مطابق نباشه:", 0, false, false, 0, Class1.ButtonOBJEee(resultend));

                                    //}
                                    #endregion

                                    else
                                    {
                                        if (count < 70)
                                        {
                                            string[] result = new string[count];
                                            string   fileid = "0";
                                            int      k      = 0;
                                            foreach (DataRow duck in mytable.Rows)
                                            {
                                                fileid = duck["fileid"].ToString();
                                                string duration  = duck["duration"].ToString();
                                                string performer = duck["performer"].ToString();
                                                string title     = duck["filename"].ToString();
                                                result[k] = "\U0001F3B5" + title + "\U0001F464" + performer;
                                                k++;
                                            }
                                            bot.SendTextMessageAsync(chatidmovaqat, mytable.Rows.Count.ToString() + "مورد مشابه یافت شد:", 0, false, false, 0, Class1.ButtonCreator(result));
                                        }
                                        else if (count >= 70)
                                        {
                                            string[] result = new string[72];
                                            string   fileid = "0";
                                            int      k      = 0;
                                            foreach (DataRow duck in mytable.Rows)
                                            {
                                                fileid = duck["fileid"].ToString();
                                                string duration  = duck["duration"].ToString();
                                                string performer = duck["performer"].ToString();
                                                string title     = duck["filename"].ToString();
                                                result[k] = "\U0001F3B5" + title + "\U0001F464" + performer;;
                                                k++;
                                                if (k > 70)
                                                {
                                                    result[71] = "\U0001F50D" + "ادامه جستجو" + e.Message.Text;
                                                    break;
                                                }
                                            }
                                            bot.SendTextMessageAsync(chatidmovaqat, mytable.Rows.Count.ToString() + "مورد مشابه یافت شد:", 0, false, false, 0, Class1.ButtonCreator(result));
                                        }
                                    }
                                }
                                else if (e.Message.Text.Contains("\U0001F50D" + "ادامه جستجو"))
                                {
                                    text = e.Message.Text.Replace("\U0001F50D" + "ادامه جستجو", "");
                                    mycommand.CommandText   = "select filename from [melo] where [filename] like '%" + text + "%'" + " or [performer] like '%" + text + "%'";
                                    myadapter.SelectCommand = mycommand;
                                    myconnection.Open();
                                    myadapter.Fill(mytable);
                                    myconnection.Close();
                                    string[] result = new string[mytable.Rows.Count - 70];
                                    int      k      = 0;
                                    int      i      = 0;
                                    foreach (DataRow duck in mytable.Rows)
                                    {
                                        if (k < 70)
                                        {
                                            k++; continue;
                                        }
                                        string title = duck["filename"].ToString();
                                        result[i] = "\U0001F3B5" + title;
                                        i++;
                                        if (i > mytable.Rows.Count)
                                        {
                                            break;
                                        }
                                    }
                                    bot.SendTextMessageAsync(chatidmovaqat, "مابقی:دی", 0, false, false, 0, Class1.ButtonCreator(result));
                                }
                            }
                            catch
                            {
                                bot.SendTextMessageAsync(e.Message.Chat.Id, "nabud");
                            }
                        }
                    }
                }
            }
            catch (Exception ex) { if (chatidmovaqat == "71869354" || chatidmovaqat == "99270771" || chatidmovaqat == "462060640")
                                   {
                                       bot.SendTextMessageAsync(chatidmovaqat, ex.ToString(), 0, false, true, e.Message.MessageId);
                                   }
            }
        }
Example #2
0
        async static void TelegramMetod()
        {
            string key = "417836710:AAHaiu8stm_QKQBiZX11MJqIcDCrOrTLyMk"; //telegram: @RandomPhoto_bot
            var    bot = new Telegram.Bot.TelegramBotClient(key);
            await bot.SetWebhookAsync("");

            int offset = 0;

            while (true)
            {
                var updates = await bot.GetUpdatesAsync(offset); // получаем массив обновлений

                foreach (var update in updates)                  // Перебираем все обновления
                {
                    var message = update.Message;
                    if (message?.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                    {
                        string rain = "";
                        if (message.Text == "/start")
                        {
                            await bot.SendTextMessageAsync(message.Chat.Id, "Привет " + message.Chat.FirstName);

                            var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                            {
                                Keyboard = new[] {
                                    new[] // row 1
                                    {
                                        new Telegram.Bot.Types.KeyboardButton("Пришли картинку"),
                                        new Telegram.Bot.Types.KeyboardButton("Пришли музыку")
                                    },
                                    new[] // row 1
                                    {
                                        new Telegram.Bot.Types.KeyboardButton("Какая погода?"),
                                        new Telegram.Bot.Types.KeyboardButton("Какая погода завтра?")
                                    },
                                },
                                ResizeKeyboard = true
                            };

                            await bot.SendTextMessageAsync(message.Chat.Id, "Выбери что хочешь получить",
                                                           ParseMode.Default, false, false, 0, keyboard, CancellationToken.None);
                        }

                        if (message.Text == "/getimage" || message.Text == "Пришли картинку")
                        {
                            string[] dirs = Directory.GetFiles(
                                @"C:\Users\workstation1\Documents\Visual Studio 2015\Projects\TelegramBotGetImage\TelegramBotGetImage\Images");
                            Random rnd     = new Random();
                            int    i       = rnd.Next(0, dirs.Length);
                            string FileUrl = dirs[i];

                            using (var stream = System.IO.File.Open(FileUrl, FileMode.Open))
                            {
                                FileToSend fts = new FileToSend();
                                fts.Content  = stream;
                                fts.Filename = FileUrl.Split('\\').Last();
                                await bot.SendPhotoAsync(message.Chat.Id, fts, "New IMG");
                            }
                        }

                        if (message.Text == "/getmusic" || message.Text == "Пришли музыку")
                        {
                            string[] dirs = Directory.GetFiles(
                                @"C:\Users\workstation1\Documents\Visual Studio 2015\Projects\TelegramBotGetImage\TelegramBotGetImage\Music");
                            Random rnd     = new Random();
                            int    w       = rnd.Next(0, dirs.Length);
                            string FileUrl = dirs[w];

                            using (var stream = System.IO.File.Open(FileUrl, FileMode.Open))
                            {
                                FileToSend fts = new FileToSend();
                                fts.Content  = stream;
                                fts.Filename = FileUrl.Split('\\').Last();
                                string[] eq       = fts.Filename.Split('-');
                                string   songName = eq.Last();
                                string   athor    = "";
                                for (int i = 0; i < eq.Length - 1; i++)
                                {
                                    athor += eq[i];
                                }
                                await bot.SendTextMessageAsync(message.Chat.Id, "Отправляю песню: " + athor + " - " + songName + " подождите");

                                await bot.SendAudioAsync(message.Chat.Id, fts, "Файл получен", 0,
                                                         athor, songName);
                            }
                        }

                        if (message.Text == "/about")
                        {
                            await bot.SendTextMessageAsync(message.Chat.Id, "Бот написан 22.09.2017\nАвтор: Тимофей Забалуев\nКонтактные данные: [email protected]");
                        }

                        if (message.Text == "/weathernow" || message.Text == "Какая погода?")
                        {
                            var q = GetSimpleWeather.WeatherGetNow();
                            //if (q.rain != null) rain = " дождь";
                            await bot.SendTextMessageAsync(message.Chat.Id, "В городе: " + q.Name + " сейчас " + q.Main.temp + " градусов");
                        }

                        if (message.Text == "/weathertomorrow" || message.Text == "Какая погода завтра?")
                        {
                            var w = GetSimpleWeather.WeatherGetFor5Days();
                            await bot.SendTextMessageAsync(message.Chat.Id, "В городе: " + w.city.name);

                            string str = " ";
                            for (int i = 1; i < 9; i++)
                            {
                                if (w.list[i].rain != null)
                                {
                                    rain = " дождь";
                                }

                                string[] split = w.list[i].dt_txt.Split(' ', ':', '-');
                                if (split[3] == "00")
                                {
                                    str += split[2] + "/" + split[1] + " "; //Выводим дополнительно число и месяц если следующий день
                                }
                                else
                                {
                                    str += "---------";
                                }
                                str += split[3] + ":00 = " + w.list[i].main.temp + "° " + rain + "\n";
                            }
                            await bot.SendTextMessageAsync(message.Chat.Id, str);
                        }
                    }
                    offset = update.Id + 1;
                }
            }
        }
Example #3
0
        async void do_work(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as String;

            try
            {
                var bot = new Telegram.Bot.TelegramBotClient(key);
                await bot.SetWebhookAsync("");

                AIMLbot.Bot lazy = new AIMLbot.Bot();


                lazy.loadSettings();
                lazy.loadAIMLFromFiles();
                lazy.isAcceptingUserInput = false;
                AIMLbot.User us = new AIMLbot.User("Username", lazy);
                lazy.isAcceptingUserInput = true;


                bot.OnCallbackQuery += async(object sc, Telegram.Bot.Args.CallbackQueryEventArgs ev) =>
                {
                    Telegram.Bot.Types.FileToSend s;
                    var message = ev.CallbackQuery.Message;
                    if (ev.CallbackQuery.Data == "callback1")
                    {
                        s = new Telegram.Bot.Types.FileToSend("https://i.pinimg.com/originals/f7/e9/80/f7e980c9700c8395535b835e66f02a59.jpg");
                    }
                    else if (ev.CallbackQuery.Data == "callback2")
                    {
                        s = new Telegram.Bot.Types.FileToSend("https://static.independent.co.uk/s3fs-public/thumbnails/image/2012/02/29/22/pg-28-sloth-cooke.jpg");
                    }
                    await bot.SendPhotoAsync(message.Chat.Id, s, "Sure! But... not today :)");

                    await bot.AnswerCallbackQueryAsync(ev.CallbackQuery.Id);
                };

                bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
                {
                    if (evu.Update.CallbackQuery != null || evu.Update.InlineQuery != null)
                    {
                        return;
                    }
                    var update  = evu.Update;
                    var message = update.Message;
                    if (message == null)
                    {
                        return;
                    }
                    if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                    {
                        if (message.Text[0] == '/')
                        {
                            if (message.Text == "/test")
                            {
                                await bot.SendTextMessageAsync(message.Chat.Id, "Yeah...",
                                                               replyToMessageId : message.MessageId);
                            }

                            if (message.Text == "/sleep")
                            {
                                var s = new Telegram.Bot.Types.FileToSend("https://beano-uploads-production.imgix.net/store/f4046f22dffe92e3f2167accb6942f788159d0f979f970dcda59f1d0e529?auto=compress&w=752&h=423&fit=min");
                                await bot.SendPhotoAsync(message.Chat.Id,
                                                         s, "Yeeeeeeeeeah, sleeeeeeeeep!");
                            }

                            if (message.Text == "/song")
                            {
                                var s = new Telegram.Bot.Types.FileToSend("http://store.naitimp3.ru/download/0/cGR1a0tRTWJwZW8wMlI2aitkT1UzVkxNdXE2dUNiRTAvcGRkeGphMTVFVTdQcGFURWlFOFQyUGZFTXJ6UVo4cWxVSUNza2NOQUpoZkJOU2ozYTJhWUpLSVdiUTRTanQrVmZnN1hQV1U5Tkk9/eels_i_need_some_sleep_(NaitiMP3.ru).mp3");
                                await bot.SendAudioAsync(message.Chat.Id, s, "", 4, "Eels", "I need some sleep...");
                            }

                            if (message.Text == "/work")
                            {
                                var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
                                    new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardButton[][]
                                {
                                    // First row
                                    new [] {
                                        // First column
                                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Work", "callback1"),

                                        // Second column
                                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Work harder", "callback2")
                                    },
                                }
                                    );

                                await bot.SendTextMessageAsync(message.Chat.Id, "Hmmmm... What should I do?..!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboard);
                            }
                        }
                        else if ((message.Text[0] >= 'а' && message.Text[0] <= 'я') || (message.Text[0] >= 'А' && message.Text[0] <= 'Я'))
                        {
                            await bot.SendTextMessageAsync(message.Chat.Id, "I'm too lazy to learn russian, sorry...",
                                                           replyToMessageId : message.MessageId);
                        }
                        else
                        {
                            AIMLbot.Request r   = new AIMLbot.Request(message.Text, us, lazy);
                            AIMLbot.Result  res = lazy.Chat(r);

                            await bot.SendTextMessageAsync(message.Chat.Id, res.Output,
                                                           replyToMessageId : message.MessageId);
                        }
                    }
                };

                bot.StartReceiving();
            }
            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #4
0
        private void processUpdate(Telegram.Bot.Types.Update update)
        {
            switch (update.Type)
            {
            case Telegram.Bot.Types.Enums.UpdateType.Message:
                var    text      = update.Message.Text;
                string imagePath = null;
                var    state     = _clientStates.ContainsKey(update.Message.Chat.Id) ? _clientStates[update.Message.Chat.Id] : null;
                if (state != null)
                {
                    switch (state.State)
                    {
                    case State.SearchMusic:
                        if (text.Equals(TEXT_BACK))
                        {
                            _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите:", replyMarkup: GetButtons());
                            _clientStates[update.Message.Chat.Id] = null;
                        }
                        else
                        {
                            var songs = GetSongsByAuthor(author: text);

                            if (songs?.Item2 != null && songs.Item2.Count > 0)
                            {
                                state.State  = State.SearchSong;
                                state.Author = text;
                                imagePath    = Path.Combine(Environment.CurrentDirectory, songs.Item1);
                                using (var stream = File.OpenRead(imagePath))
                                {
                                    var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: state.Author).Result;
                                }
                                _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите название песни:", replyMarkup: getSongsButtons(songs.Item2));
                            }
                            else
                            {
                                _client.SendTextMessageAsync(update.Message.Chat.Id, "Ничего не найдено\nВведите автора:", replyMarkup: getAuthors());
                            }
                        }
                        break;

                    case State.SearchSong:
                        if (text.Equals(TEXT_BACK))
                        {
                            state.State = State.SearchMusic;
                            _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите автора:", replyMarkup: getAuthors());
                        }
                        else
                        {
                            var songPath = getSongPath(text);
                            var songs2   = GetSongsByAuthor(author: state.Author);
                            if (!string.IsNullOrEmpty(songPath) && File.Exists(songPath))
                            {
                                _client.SendTextMessageAsync(update.Message.Chat.Id, "Песня загружается...");

                                using (var stream = File.OpenRead(songPath))
                                {
                                    var r = _client.SendAudioAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), replyMarkup: getSongsButtons(songs2.Item2)).Result;
                                }
                            }
                            else
                            {
                                _client.SendTextMessageAsync(update.Message.Chat.Id, "Ничего не найдено\nВведите название песни:", replyMarkup: getSongsButtons(songs2.Item2));
                            }
                        }
                        break;
                    }
                }
                else
                {
                    switch (text)
                    {
                    case TEXT_MUSIC:
                        _clientStates[update.Message.Chat.Id] = new UserState {
                            State = State.SearchMusic
                        };
                        _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите автора:", replyMarkup: getAuthors());
                        break;

                    case TEXT_1:
                        imagePath = Path.Combine(Environment.CurrentDirectory, "1.png");
                        using (var stream = File.OpenRead(imagePath))
                        {
                            var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: "1", replyMarkup: GetInlineButton(1)).Result;
                        }
                        break;

                    case TEXT_2:
                        imagePath = Path.Combine(Environment.CurrentDirectory, "2.png");
                        using (var stream = File.OpenRead(imagePath))
                        {
                            var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: "2", replyMarkup: GetInlineButton(2)).Result;
                        }
                        break;

                    case TEXT_3:
                        imagePath = Path.Combine(Environment.CurrentDirectory, "3.png");
                        using (var stream = File.OpenRead(imagePath))
                        {
                            var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: "3", replyMarkup: GetInlineButton(3)).Result;
                        }
                        break;

                    case TEXT_4:
                        imagePath = Path.Combine(Environment.CurrentDirectory, "4.png");
                        using (var stream = File.OpenRead(imagePath))
                        {
                            var r = _client.SendPhotoAsync(update.Message.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(stream), caption: "4", replyMarkup: GetInlineButton(4)).Result;
                        }
                        break;

                    default:
                        _client.SendTextMessageAsync(update.Message.Chat.Id, "Receive text :" + text, replyMarkup: GetButtons());
                        break;
                    }
                }
                break;

            case Telegram.Bot.Types.Enums.UpdateType.CallbackQuery:
                switch (update.CallbackQuery.Data)
                {
                case "1":
                    var msg1 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, $"Заказ `{update.CallbackQuery.Data}` принят", replyMarkup: GetButtons()).Result;
                    break;

                case "2":
                    var msg2 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, $"Заказ `{update.CallbackQuery.Data}` принят", replyMarkup: GetButtons()).Result;
                    break;

                case "3":
                    var msg3 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, $"Заказ `{update.CallbackQuery.Data}` принят", replyMarkup: GetButtons()).Result;
                    break;

                case "4":
                    var msg4 = _client.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, $"Заказ `{update.CallbackQuery.Data}` принят", replyMarkup: GetButtons()).Result;
                    break;
                }
                break;

            default:
                Console.WriteLine(update.Type + " Not ipmlemented!");
                break;
            }
        }