private static void ConvertSendToTG(
            Telegram.Bot.Types.Chat target,
            cqhttp.Cyan.Messages.Message message,
            string sender_nick
            )
        {
            foreach (var i in message.data)
            {
                switch (i.type)
                {
                case "text":
                    OptimisticModuleManager.SendText(target, $"[{NicknameLookup.GetCQNickname(sender_nick)}] {i.data["text"]}");
                    break;

                case "image":
                    OptimisticModuleManager.SendText(target, $"{NicknameLookup.GetCQNickname(sender_nick)}发送了图片");
                    OptimisticModuleManager.SendPhoto(target, i.data["url"]);
                    break;

                case "face":
                    OptimisticModuleManager.SendText(target, $"[{NicknameLookup.GetCQNickname(sender_nick)}] " +
                                                     $"{ConvertEmoji(Convert.ToInt32(i.data["id"]))}");
                    break;
                }
            }
        }
 public static Chat ToDomain(this Telegram.Bot.Types.Chat chat) =>
 new Chat
 {
     IsPrivate      = chat.Type == ChatType.Private,
     TelegramChatId = chat.Id,
     UserName       = chat.Username
 };
Beispiel #3
0
        public User GetUser(Telegram.Bot.Types.Chat c)
        {
            var user = _db.Set <User>().SingleOrDefault(x => x.Id == c.Id);

            if (user != null)
            {
                if (user.Title != c.Title)
                {
                    user.Title = c.Title;

                    lock (_dbLock)
                    {
                        _db.SaveChanges();
                    }
                }
            }
            else
            {
                user = User.New(c.Id, c.Title, c.Username, "", "", "en", (int)c.Type);

                lock (_dbLock)
                {
                    _db.Add(user);
                    _db.SaveChanges();
                }
            }

            return(user);
        }
Beispiel #4
0
        private async Task UpdateUser(App app, TelegramUser from, TelegramChat chat,
                                      CancellationToken ct)
        {
            var chatId = GetChatId(chat);

            var username = from.Username;

            if (string.IsNullOrWhiteSpace(username))
            {
                await SendMessageAsync(GetUserNotFoundMessage(app), chatId, ct);

                return;
            }

            var user = await userStore.GetByPropertyAsync(app.Id, TelegramIntegration.UserUsername.Name, username, ct);

            if (user == null)
            {
                await SendMessageAsync(GetUserNotFoundMessage(app), chatId, ct);

                return;
            }

            await userStore.UpsertAsync(app.Id, user.Id, new SetUserProperty
            {
                Property      = TelegramIntegration.UserUsername.Name,
                PropertyValue = chatId,
            }, ct);

            await SendMessageAsync(GetUserLinkedMessage(app), chatId, ct);
        }
Beispiel #5
0
        public void ShowCurrencyRate(Telegram.Bot.Types.Chat chat, string text)
        {
            Exchange exchange = new Exchange();

            BotClient.SendTextMessageAsync(
                chatId: chat,
                text: exchange.GetRate(text)
                );
        }
Beispiel #6
0
        private static (BotCommands, System.Reflection.MethodInfo[]) Bot_OnNewUser(Telegram.Bot.Types.Chat chat, Telegram.Bot.Types.User user)
        {
            Commands c = new Commands(chat);

            System.Reflection.MethodInfo[] m = c.GetType().GetMethods()
                                               .Where(d => d.ReturnType == typeof(Task) && BotController.CheckParams(d.GetParameters()))
                                               .ToArray();
            return(c, m);
        }
Beispiel #7
0
        public static Tables.Chat GenChat(Telegram.Bot.Types.Chat chat)
        {
            _ = chat ?? throw new ArgumentNullException(nameof(chat));

            return(new Tables.Chat()
            {
                Id = chat.Id,
                Title = chat.Title,
                Description = chat.Description
            });
        }
Beispiel #8
0
        public static Chat FromTelegramChat(Telegram.Bot.Types.Chat chat)
        {
            if (chat == null)
            {
                return(null);
            }
            Chat c = new Chat(ClientId, (ulong)chat.Id, FromTelegramChatType(chat.Type));

            c.Title = chat.Title;

            return(c);
        }
Beispiel #9
0
        public Chat FindOrInsertChat(Telegram.Bot.Types.Chat incomeChat)
        {
            Chat chat = new Chat(incomeChat);

            SqliteCommand cmd = DB.DBConnection.Connection.CreateCommand();

            cmd.CommandText = $"select * from chat where id = '{incomeChat.Id}'";

            try
            {
                var reader = cmd.ExecuteReader();
                if (!reader.HasRows)
                {
                    reader.Close();
                    cmd.CommandText =
                        $"INSERT INTO chat(id, username, firstname, lastname) VALUES ('{incomeChat.Id}', '{incomeChat.Username}', '{incomeChat.FirstName}', '{incomeChat.LastName}')";
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    while (reader.Read())
                    {
                        var value = reader["isAdmin"].ToString();
                        if (value != "")
                        {
                            chat.IsAdmin = Convert.ToBoolean(value);
                        }
                        value = reader["tournament_id"].ToString();
                        if (value != "")
                        {
                            chat.Tournament = GetTournament(Convert.ToInt32(value));
                        }
                        value = reader["season_id"].ToString();
                        if (value != "")
                        {
                            chat.Season = GetSeason(Convert.ToInt32(value));
                        }
                    }
                }
            }
            catch (SqliteException ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(chat);
        }
Beispiel #10
0
 internal void LogMessage(Telegram.Bot.Types.Chat from, int messageId, string text, string data)
 {
     RunIsolatedDb(db =>
     {
         var msg = new Message
         {
             CallbackQueryData = data,
             CreateDate        = DateTime.Now,
             FromUser          = true,
             UserId            = GetUser(from).Id,
             TelegramMessageId = messageId,
             Text = text
         };
         db.Add(msg);
         db.SaveChanges();
     });
 }
Beispiel #11
0
        public async Task Execute(IJobExecutionContext context)
        {
            JobDataMap data = context.MergedJobDataMap;

            TelegramBotClient client = (TelegramBotClient)data["client"];
            DataBase          db     = Singleton.GetInstance().Context;

            Channel[] channels = db.GetChannels();

            foreach (Channel channel in channels)
            {
                Telegram.Bot.Types.Chat channelInfo = await client.GetChatAsync(channel.IDChannel);

                if (channelInfo.PinnedMessage != null)
                {
                    await client.UnpinChatMessageAsync(channelInfo.Id);
                }
            }
        }
Beispiel #12
0
        public bool UpdateInfo(Telegram.Bot.Types.Chat nowChat, TelegramBotClient client)
        {
            var needSave = false;
            var count    = client.GetChatMembersCountAsync(Id_tg).Result;

            if (count != CountMembers)
            {
                CountMembers = count;
                needSave     = true;
            }

            if (nowChat.Title != Name)
            {
                Name     = nowChat.Title;
                needSave = true;
            }

            return(needSave);
        }
Beispiel #13
0
        public void Register(Telegram.Bot.Types.Chat chat, User user)
        {
            if (_administrators.Any(x => x.ChatId == chat.Id))
            {
                return;
            }

            var uow           = _uowFactory();
            var administrator = uow.ChatAdministrators.FirstOrDefault(x => x.ChatId == chat.Id)
                                ?? new ChatAdministrator
            {
                ChatId   = chat.Id,
                UserId   = user.Id,
                UserName = chat.Username
            };

            administrator.DateModified = DateTime.Now;
            _administrators.Add(administrator);
            uow.ChatAdministrators.Merge(administrator);
        }
Beispiel #14
0
        static ChatRoomFlow GetOrCreate(Telegram.Bot.Types.Chat chat)
        {
            if (_chats.TryGetValue(chat.Id, out var existedChatRoom))
            {
                return(existedChatRoom);
            }

            var newChat     = new Chat(_botClient, chat);
            var newChatRoom = new ChatRoomFlow(newChat)
            {
                YaDictionaryApi = _yapiDicClient,
                YaTranslateApi  = _yapiTransClient,
                WordsService    = _wordsService
            };
            var task = newChatRoom.Run();

            task.ContinueWith((t) => Botlog.Write($"faulted {t.Exception}"), TaskContinuationOptions.OnlyOnFaulted);
            _chats.TryAdd(chat.Id, newChatRoom);
            return(null);
        }
Beispiel #15
0
        private static ChatRoomFlow GetOrCreate(Telegram.Bot.Types.Chat chat)
        {
            if (Chats.TryGetValue(chat.Id, out var existedChatRoom))
            {
                return(existedChatRoom);
            }

            var newChatRoom = new ChatRoomFlow(
                new ChatIO(_botClient, chat),
                new TelegramUserInfo(chat.Id, chat.FirstName, chat.LastName, chat.Username),
                _settings,
                _addWordService,
                _userWordService,
                _userService);

            var task = newChatRoom.Run();

            task.ContinueWith((t) => Botlog.Error(chat.Id, $"Faulted {t.Exception}"), TaskContinuationOptions.OnlyOnFaulted);
            Chats.TryAdd(chat.Id, newChatRoom);
            return(newChatRoom);
        }
Beispiel #16
0
        public User Login(Telegram.Bot.Types.Chat chat, string email, string password)
        {
            var uow = _uowFactory();

            if (_administrators.Find(x => x.ChatId == chat.Id) is { } signed)
            {
                return(uow.Users.FindById(signed.UserId));
            }

            var user = _password.Equals(password, StringComparison.Ordinal)
                ? uow.Users.FirstOrDefault(x => x.Email.Equals(email, StringComparison.OrdinalIgnoreCase))
                : null;

            if (user != null &&
                uow.ChatAdministrators.FirstOrDefault(x => x.ChatId == chat.Id) is { } administrator)
            {
                _administrators.Add(administrator);
            }

            return(user);
        }
Beispiel #17
0
        private static string getChatNome(Telegram.Bot.Types.ChatId chatID)
        {
            string nomeChat = null;

            try
            {
                Telegram.Bot.Types.Chat chat = botClient.GetChatAsync(chatID).Result;

                if (chat.Type == Telegram.Bot.Types.Enums.ChatType.Channel || chat.Type == Telegram.Bot.Types.Enums.ChatType.Group || chat.Type == Telegram.Bot.Types.Enums.ChatType.Supergroup && chat.Title.Length > 0)
                {
                    nomeChat += chat.Title;
                }
                if (chat.Type == Telegram.Bot.Types.Enums.ChatType.Private && chat.FirstName.Length > 0)
                {
                    if (!String.IsNullOrEmpty(nomeChat))
                    {
                        nomeChat += ' ';
                    }
                    nomeChat += chat.FirstName;
                }
                if (chat.Type == Telegram.Bot.Types.Enums.ChatType.Private && chat.LastName.Length > 0)
                {
                    if (!String.IsNullOrEmpty(nomeChat))
                    {
                        nomeChat += ' ';
                    }
                    nomeChat += chat.LastName;
                }
            }
            catch
            {
                nomeChat = "indefinido";
            }

            return(nomeChat);
        }
Beispiel #18
0
 public BotCommands(Telegram.Bot.Types.Chat chat, DataDict data)
 {
     Chat = chat;
     Data = data;
 }
        /// <summary>
        /// Получить объект чата по объекту телеграма
        /// </summary>
        /// <param name="applicationContext">Контекст базы данных</param>
        /// <param name="telegramChat">Объект телеграма</param>
        /// <returns>Объект чата</returns>
        public static async Task <Chat> GetChatFromTelegramModel(this ApplicationContext applicationContext, TelegramChat telegramChat)
        {
            ExceptionHelper.ThrowIfNull(telegramChat, "telegramChat");
            var chat = await applicationContext.FindChatByTelegramId(telegramChat.Id);

            if (chat == null)
            {
                chat = new Chat()
                {
                    TelegramId       = telegramChat.Id,
                    FirstName        = telegramChat.FirstName,
                    LastName         = telegramChat.LastName,
                    Username         = telegramChat.Username,
                    Title            = telegramChat.Title,
                    Description      = telegramChat.Description,
                    TelegramChatType = telegramChat.Type
                };

                await applicationContext.Chats
                .AddAsync(chat)
                .ConfigureAwait(false);

                await applicationContext.SaveChangesAsync();
            }

            return(chat);
        }
Beispiel #20
0
 public Chat(Telegram.Bot.Types.Chat botChat)
 {
     BotChat         = botChat;
     WaitingCommands = new List <Command>();
 }
Beispiel #21
0
 private static string GetChatId(TelegramChat chat)
 {
     return(chat.Id.ToString(CultureInfo.InvariantCulture) !);
 }