Inheritance: System.Web.UI.Page
Ejemplo n.º 1
0
        public FrmCTHDN()
        {
            Sender = new SendMessage(GetMessage);
            InitializeComponent();

            _DSSP = svsp.LayTatCaSanPham().ToList();
            dtgTenSP.DataSource = _DSSP;
            dtgTenSP.DisplayMember = "TenSP";
            dtgTenSP.ValueMember = "MaSP";

            _DSSIZE = svsize.LayTatCaSize().ToList();
            dtgSize.DataSource = _DSSIZE;
            dtgSize.DisplayMember = "Size1";
            dtgSize.ValueMember = "MaSize";

            _DSMAU = svm.LayTatCaMau().ToList();
            dtgMau.DataSource = _DSMAU;
            dtgMau.DisplayMember = "TenMau";
            dtgMau.ValueMember = "MaMau";

            _DSNCC = svncc.LayTatCaNhaCungCap().ToList();
            cbNCC.DataSource = _DSNCC;
            cbNCC.DisplayMember = "TenNCC";
            cbNCC.ValueMember = "MaNCC";

            dtgChitiethoadon.AllowUserToAddRows = true;
        }
Ejemplo n.º 2
0
 public ChannelList(string ServerName)
     : base(ServerName)
 {
     _servername = ServerName;
     sAntiFlood = sIrcBase.Networks[ServerName].sAntiFlood;
     sSendMessage = sIrcBase.Networks[ServerName].sSendMessage;
 }
Ejemplo n.º 3
0
 public CtcpSender(string ServerName)
     : base(ServerName)
 {
     _userInfoMessage = "Schumix CTCP";
     _fingerMessage = _userInfoMessage;
     _versionMessage = string.Format("Schumix {0}\n{1} {2}\n{3} {4}", sUtilities.GetVersion(), sLConsole.GetString("Operating System:"), sPlatform.GetOSName(), sLConsole.GetString("Processor:"), sUtilities.GetCpuId());
     _sourceMessage = Consts.SchumixWebsite;
     _clientInfoMessage = sLConsole.GetString("This client supports: UserInfo, Finger, Version, Source, Ping, Time and ClientInfo");
     sSendMessage = sIrcBase.Networks[ServerName].sSendMessage;
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Вызов события об успешной отправки данных
 /// </summary>
 /// <param name="send_size"></param>
 internal void CallSend(int send_size)
 {
     Task.Factory.StartNew(() => { SendMessage?.Invoke(this, new SendClientArgs(send_size)); });
 }
Ejemplo n.º 5
0
        public static int InsertUpdateRecommendation(Recommendation recommendation)
        {
            try
            {
                string procedureName = "TRecommendation_INS_UPD";
                Log.LogInfo("recommendation name: " + recommendation.nvFirstName + " " + recommendation.nvLastName);
                if (recommendation.oCategoryItem.iCatItemId == 0)
                {
                    procedureName = "TRecommendation_INS_NewDoctor";
                    recommendation.oCategoryItem.bNew = true;
                    Log.LogInfo("recommendation.oCategoryItem.bNew: " + recommendation.oCategoryItem.bNew);
                    Log.LogInfo("recommendation.oCategoryItem.iCatItemParentId: " + recommendation.oCategoryItem.iCatItemParentId);
                    recommendation.oCategoryItem = CategoryItem.InsertUpdateCategoryItem(1, recommendation.oCategoryItem);                    //TODO: change iUserId = 1
                    if (recommendation.oCategoryItem == null)
                    {
                        return(-1);
                    }
                }
                if (recommendation.iFlexibilityType <= 3 && recommendation.iFlexibilityType > 0)
                {
                    recommendation.iFlexibilityType += 3;
                }
                if (recommendation.iHumanityType <= 3 && recommendation.iHumanityType > 0)
                {
                    recommendation.iHumanityType += 3;
                }
                if (recommendation.iKindnessType <= 3 && recommendation.iKindnessType > 0)
                {
                    recommendation.iKindnessType += 3;
                }

                recommendation.iCatItemId = recommendation.oCategoryItem.iCatItemId;
                Log.LogInfo("recommendation.iCatItemId:" + recommendation.iCatItemId);
                if (recommendation.nvFilePath != null && recommendation.nvFilePath.IndexOf("data:") != -1)
                {
                    string path = recommendation.nvFilePath.Substring(recommendation.nvFilePath.IndexOf("data:"));
                    string name = recommendation.nvFilePath.IndexOf("name:") != -1 ? recommendation.nvFilePath.Substring(recommendation.nvFilePath.IndexOf("name:") + 5, recommendation.nvFilePath.IndexOf(";") - 5) : "";
                    recommendation.nvFilePath = Fileshandler.SaveFileByBase64(path, name);
                }
                //Log.LogInfo("recommendation.nvFilePath: " + recommendation.nvFilePath);
                DataSet ds = SqlDataAccess.ExecuteDatasetSP(procedureName, ObjectGenerator <Recommendation> .GetSqlParametersFromObject(recommendation));
                int     iRecommendationId = 0;
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    iRecommendationId = int.Parse(ds.Tables[0].Rows[0][0].ToString());
                }
                else
                {
                    return(iRecommendationId);
                }
                if (recommendation.nvMail != null && recommendation.nvMail != "")
                {
                    //SendMessage.SendEmailOrFax("", recommendation.nvMail, "פרס דניאלי", "תודה על השתתפותך במיזם פרס דניאלי - רפואה עם לב");
                    SendMessage.SendEmail(recommendation.nvMail).Wait();
                }
                Log.LogInfo("recommendation.nvMail: " + recommendation.nvMail);
                return(iRecommendationId);
            }
            catch (Exception ex)
            {
                Log.LogError("InsertUpdateRecommendation / TRecommendation_INS_UPD",
                             //"recommendation = " + JsonConvert.SerializeObject(recommendation) +
                             ", exception = " + ex);
                return(-1);
            }
        }
Ejemplo n.º 6
0
        public static async Task AntiSpamMeasure(TelegramBotAbstract telegramBotClient, MessageEventArgs e,
                                                 SpamType checkSpam)
        {
            if (checkSpam == SpamType.ALL_GOOD)
            {
                return;
            }

            await RestrictUser.Mute(60 * 5, telegramBotClient, e.Message.Chat.Id, e.Message.From.Id);

            var language = e.Message.From.LanguageCode.ToLower();

            switch (checkSpam)
            {
            case SpamType.SPAM_LINK:
            {
                var text2 = new Language(new Dictionary <string, string>
                    {
                        { "en", "You sent a message with spam, and you were muted for 5 minutes" },
                        { "it", "Hai inviato un messaggio con spam, e quindi il bot ti ha mutato per 5 minuti" }
                    });


                await SendMessage.SendMessageInPrivate(telegramBotClient, e, text2);

                break;
            }

            case SpamType.NOT_ALLOWED_WORDS:
            {
                var text2 = new Language(new Dictionary <string, string>
                    {
                        { "en", "You sent a message with banned words, and you were muted for 5 minutes" },
                        { "it", "Hai inviato un messaggio con parole bandite, e quindi il bot ti ha mutato per 5 minuti" }
                    });

                await SendMessage.SendMessageInPrivate(telegramBotClient, e, text2);

                break;
            }

            case SpamType.FOREIGN:
            {
                var text2 = new Language(new Dictionary <string, string>
                    {
                        { "en", "You sent a message with banned characters, and you were muted for 5 minutes" },
                        {
                            "it",
                            "Hai inviato un messaggio con caratteri banditi, e quindi il bot ti ha mutato per 5 minuti"
                        }
                    });

                await SendMessage.SendMessageInPrivate(telegramBotClient, e, text2);

                break;
            }

            // ReSharper disable once UnreachableSwitchCaseDueToIntegerAnalysis
            case SpamType.ALL_GOOD:
                return;

            default:
                throw new ArgumentOutOfRangeException(nameof(checkSpam), checkSpam, null);
            }

            await telegramBotClient.DeleteMessageAsync(e.Message.Chat.Id, e.Message.MessageId, e.Message.Chat.Type);
        }
Ejemplo n.º 7
0
        public async Task<bool> CreatePost(string messageUserId, string post,
            UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var url = string.Format(EndPoints.CreatePost, user.Region, messageUserId);
                const string boundary = "abcdefghijklmnopqrstuvwxyz";
                var messageJson = new SendMessage
                {
                    message = new Message()
                    {
                        body = post,
                        fakeMessageUid = 1384958573288,
                        messageKind = 1
                    }
                };

                var json = JsonConvert.SerializeObject(messageJson);
                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                stringContent.Headers.Add("Content-Description", "message");
                var form = new MultipartContent("mixed", boundary) { stringContent };
                var result = await _webManager.PostData(new Uri(url), form, null, userAccountEntity);
                return result.IsSuccess;
            }
            catch (Exception ex)
            {

                throw new Exception("Failed to send post", ex);
            }
        }
        public async Task<Result> CreateNewGroupMessageWithMedia(string[] toArray, string message, string imagePath, Stream realImage, UserAuthenticationEntity currentTokens, string region)
        {
            var url = string.Format(EndPoints.CreateNewGroupPost, region);
            const string boundary = "gc0p4Jq0M2Yt08jU534c0p";
            var messageJson = new SendMessage
            {
                to = toArray,
                message = new Message()
                {
                    body = message,
                    fakeMessageUid = 1234,
                    messageKind = 3
                }
            };

            var json = JsonConvert.SerializeObject(messageJson);
            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
            stringContent.Headers.Add("Content-Description", "message");
            var form = new MultipartContent("mixed", boundary) { stringContent };
            var t = new StreamContent(realImage);
            t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            t.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            t.Headers.Add("Content-Description", "image-data-0");
            t.Headers.Add("Content-Transfer-Encoding", "binary");
            t.Headers.ContentLength = realImage.Length;
            form.Add(t);

            return await _webManager.PostData(new Uri(url), form, currentTokens, "ja", true);
        }
Ejemplo n.º 9
0
        public static void RunBot(string accessToken)
        {
            var bot = new TelegramBot(accessToken);

            var me = bot.MakeRequestAsync(new GetMe()).Result;
            if (me == null)
            {
                Console.WriteLine("GetMe() FAILED. Do you forget to add your AccessToken to config.json?");
                Console.WriteLine("(Press ENTER to quit)");
                Console.ReadLine();
                return;
            }
            Console.WriteLine("{0} (@{1}) connected!", me.FirstName, me.Username);

            Console.WriteLine();
            Console.WriteLine("Find @{0} in Telegram and send him a message - it will be displayed here", me.Username);
            Console.WriteLine("(Press ENTER to stop listening and quit)");
            Console.WriteLine();

            string uploadedPhotoId = null;
            string uploadedDocumentId = null;
            long offset = 0;
            while (!stopMe)
            {
                var updates = bot.MakeRequestAsync(new GetUpdates() { Offset = offset }).Result;
                if (updates != null)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1;
                        if (update.Message == null)
                        {
                            continue;
                        }
                        var from = update.Message.From;
                        var text = update.Message.Text;
                        var photos = update.Message.Photo;
                        Console.WriteLine(
                            "Msg from {0} {1} ({2}) at {4}: {3}",
                            from.FirstName,
                            from.LastName,
                            from.Username,
                            text,
                            update.Message.Date);

                        if (photos != null)
                        {
                            var webClient = new WebClient();
                            foreach (var photo in photos)
                            {
                                Console.WriteLine("  New image arrived: size {1}x{2} px, {3} bytes, id: {0}", photo.FileId, photo.Height, photo.Width, photo.FileSize);
                                var file = bot.MakeRequestAsync(new GetFile(photo.FileId)).Result;
                                var tempFileName = System.IO.Path.GetTempFileName();
                                webClient.DownloadFile(file.FileDownloadUrl, tempFileName);
                                Console.WriteLine("    Saved to {0}", tempFileName);
                            }
                        }

                        if (string.IsNullOrEmpty(text))
                        {
                            continue;
                        }
                        if (text == "/photo")
                        {
                            if (uploadedPhotoId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_photo");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var photoData = typeof(Program).Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.t_logo.png"))
                                {
                                    var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(photoData, "Telegram_logo.png"))
                                    {
                                        Caption = "Telegram_logo.png"
                                    };
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedPhotoId = msg.Photo.Last().FileId;
                                }
                            }
                            else
                            {
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(uploadedPhotoId))
                                {
                                    Caption = "Resending photo id=" + uploadedPhotoId
                                };
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/doc")
                        {
                            if (uploadedDocumentId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var docData = typeof(Program).Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.Telegram_Bot_API.htm"))
                                {
                                    var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Telegram_Bot_API.htm"));
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedDocumentId = msg.Document.FileId;
                                }
                            }
                            else
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(uploadedDocumentId));
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/docutf8")
                        {
                            var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                            bot.MakeRequestAsync(reqAction).Wait();
                            System.Threading.Thread.Sleep(500);
                            using (var docData = typeof(Program).Assembly.GetManifestResourceStream("TelegramBotDemo-vNext.Пример UTF8 filename.txt"))
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Пример UTF8 filename.txt"));
                                var msg = bot.MakeRequestAsync(req).Result;
                                uploadedDocumentId = msg.Document.FileId;
                            }
                            continue;
                        }
                        if (text == "/help")
                        {
                            var keyb = new ReplyKeyboardMarkup()
                            {
                                Keyboard = new[] { new[] { "/photo", "/doc", "/docutf8" }, new[] { "/help" } },
                                OneTimeKeyboard = true,
                                ResizeKeyboard = true
                            };
                            var reqAction = new SendMessage(update.Message.Chat.Id, "Here is all my commands") { ReplyMarkup = keyb };
                            bot.MakeRequestAsync(reqAction).Wait();
                            continue;
                        }
                        if (update.Message.Text.Length % 2 == 0)
                        {
                            bot.MakeRequestAsync(new SendMessage(
                                update.Message.Chat.Id,
                                "You wrote *" + update.Message.Text.Length + " characters*")
                            {
                                ParseMode = SendMessage.ParseModeEnum.Markdown
                            }).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }
Ejemplo n.º 10
0
        private async Task <bool> SendGeneralSms(string messages, string sender, string phonenumber)
        {
            var cred = GetSmsCredentials();

            // Get the SMS Provider
            switch (Enum.Parse(typeof(SMSProviderEnum), cred.ActiveSmsProvider))
            {
            case SMSProviderEnum.Twilio:
                // Twilio SMS Credentials
                var appSettingsSection = _config.GetSection("TwilioKey");
                var appSettings        = appSettingsSection.Get <TwilioKey>();

                //Check Intervals
                var twi_message = SendMessage
                                  .SendSingleMessage(appSettings.ACCOUNTSID, appSettings.AUTHTOKEN, messages, sender, phonenumber);
                break;

            case SMSProviderEnum.Nexmo:

                //Nexmo SMS Credentials
                var appNex         = _config.GetSection("NexmoKey");
                var appSettingsNex = appNex.Get <NexmoKey>();

                var nex_message = SendNexmoMessage
                                  .SendSingleNexmoMessage(appSettingsNex.APIKEY, appSettingsNex.APISECRET, messages, sender, phonenumber);
                break;

            case SMSProviderEnum.SMSProviderNG:
                //SMS Provider NG Credentials
                var apppProv        = _config.GetSection("SMSProviderNGKey");
                var appSettingsProv = apppProv.Get <SMSProviderNGKey>();

                string message = SMSProviderNGsms.SendSingleSMSProviderMessage(appSettingsProv.USERNAME, appSettingsProv.PASSWORD,
                                                                               messages, sender, phonenumber);

                ResponseResult value = JsonConvert.DeserializeObject <ResponseResult>(message);
                if (value.status == "OK")
                {
                    //Log Sent message
                    TSmsLog newrec = new TSmsLog
                    {
                        Sendimmediately = true,
                        Datetosend      = DateTime.Now,
                        CanSend         = true,
                        Name            = sender,
                        From            = sender,
                        Sent            = true,
                        To           = phonenumber,
                        Message      = messages,
                        ErrorMessage = message,
                        Subject      = sender,
                        Createdby    = "Anonymous",
                    };
                    await LogSms(newrec);
                }
                else
                {
                    //Log Sent message
                    TSmsLog newrec = new TSmsLog
                    {
                        Sendimmediately = true,
                        Datetosend      = DateTime.Now,
                        CanSend         = true,
                        Name            = sender,
                        From            = sender,
                        Message         = messages,
                        ErrorMessage    = message,
                        Sent            = false,
                        To        = phonenumber,
                        Subject   = sender,
                        Createdby = "Anonymous",
                    };
                    await LogSms(newrec);
                }

                break;

            default:
                break;
            }
            return(true);
        }
Ejemplo n.º 11
0
    public void connect()
    {
        SendMessage connect = new SendMessage("0", "CONNECTION", new string[] { email.text, password.text });

        sendMessage(connect);
    }
Ejemplo n.º 12
0
        public virtual Task <Unit> SendMessage(string roomId, SendMessage message, string accessToken)
        {
            var arguments = new object[] { roomId, message, accessToken };

            return((Task <Unit>)methodImpls["SendMessage"](Client, arguments));
        }
Ejemplo n.º 13
0
 private void OnSendMessage(string msg)
 {
     SendMessage?.Invoke(this, msg);
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Use send_message to record when a user sends a message to other i.e. seller, support.
        /// </summary>
        /// <exception cref="ai.thirdwatch.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="JSON">Pass message to thirdwatch. Only &#x60;_userID&#x60; is required field. But this should contain message info.</param>
        /// <returns>Task of ApiResponse (EventResponse)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <EventResponse> > SendMessageAsyncWithHttpInfo(SendMessage JSON)
        {
            // verify the required parameter 'JSON' is set
            if (JSON == null)
            {
                throw new ApiException(400, "Missing required parameter 'JSON' when calling SendMessageApi->SendMessage");
            }

            var    localVarPath         = "/v1/send_message";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (JSON != null && JSON.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(JSON); // http body (model) parameter
            }
            else
            {
                localVarPostBody = JSON; // byte array
            }

            // authentication (api_key) required
            if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("X-THIRDWATCH-API-KEY")))
            {
                localVarHeaderParams["X-THIRDWATCH-API-KEY"] = Configuration.GetApiKeyWithPrefix("X-THIRDWATCH-API-KEY");
            }

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                       Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                       localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("SendMessage", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <EventResponse>(localVarStatusCode,
                                                   localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                   (EventResponse)Configuration.ApiClient.Deserialize(localVarResponse, typeof(EventResponse))));
        }
Ejemplo n.º 15
0
 public virtual Task<Unit> SendMessage(string roomId,SendMessage message,string accessToken)
 {
     var arguments = new object[] { roomId,message,accessToken };
     return (Task<Unit>) methodImpls["SendMessage"](Client, arguments);
 }
Ejemplo n.º 16
0
        public async Task <bool> CreatePostWithMedia(string messageUserId, string post, String path, byte[] fileStream,
                                                     UserAccountEntity userAccountEntity)
        {
            try
            {
                var          user        = userAccountEntity.GetUserEntity();
                var          url         = string.Format(EndPoints.CreatePost, user.Region, messageUserId);
                const string boundary    = "abcdefghijklmnopqrstuvwxyz";
                var          messageJson = new SendMessage
                {
                    message = new Message()
                    {
                        body           = post,
                        fakeMessageUid = 1384958573288,
                        messageKind    = 1
                    }
                };

                var json          = JsonConvert.SerializeObject(messageJson);
                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                stringContent.Headers.Add("Content-Description", "message");
                var form = new MultipartContent("mixed", boundary)
                {
                    stringContent
                };

                Stream stream = new MemoryStream(fileStream);
                var    t      = new StreamContent(stream);
                var    s      = Path.GetExtension(path);
                if (s != null && s.Equals(".png"))
                {
                    t.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                }
                else
                {
                    var extension = Path.GetExtension(path);
                    if (extension != null && (extension.Equals(".jpg") || extension.Equals(".jpeg")))
                    {
                        t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                    }
                    else
                    {
                        t.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
                    }
                }
                t.Headers.ContentType        = new MediaTypeHeaderValue("image/jpeg");
                t.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                t.Headers.Add("Content-Description", "image-data-0");
                t.Headers.Add("Content-Transfer-Encoding", "binary");
                t.Headers.ContentLength = stream.Length;
                form.Add(t);

                var result = await _webManager.PostData(new Uri(url), form, null, userAccountEntity);

                return(result.IsSuccess);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to send post (with media)", ex);
            }
        }
Ejemplo n.º 17
0
        private static async Task RunBot()
        {
            try
            {
                var bot = new TelegramBot(BotToken);

                var me = await bot.MakeRequestAsync(new GetMe());

                var db = new MaterialtelegramBotdbEntities();

                long       offset  = 0;
                var        whatDo  = 0;
                const long adminId = 87310097;

                while (true)
                {
                    var updates = await bot.MakeRequestAsync(new GetUpdates()
                    {
                        Offset = offset
                    });

                    foreach (var item in updates)
                    {
                        try
                        {
                            var qGetBotUser = (from a in db.Users
                                               where a.UserID.Equals(item.Message.Chat.Id)
                                               select a).SingleOrDefault();

                            if (qGetBotUser == null)
                            {
                                var botUser = new User
                                {
                                    UserID    = item.Message.Chat.Id,
                                    FirstName = item.Message.Chat.FirstName,
                                    LastName  = item.Message.Chat.LastName,
                                    UserName  = item.Message.Chat.Username
                                };

                                db.Users.Add(botUser);
                                db.SaveChanges();
                            }

                            offset = item.UpdateId + 1;

                            var id        = item.Message.Chat.Id;
                            var userText  = item.Message.Text;
                            var from      = item.Message.From;
                            var photos    = item.Message.Photo;
                            var contact   = item.Message.Contact;
                            var location  = item.Message.Location;
                            var queryBack = item.CallbackQuery;

                            var qGet = (from a in db.Settings
                                        where a.Id.Equals(1)
                                        select a).SingleOrDefault();

                            var checkUser = new GetChatMember(qGet.Channel ?? 0, id);
                            var isUser    = await bot.MakeRequestAsync(checkUser);

                            var isBotLock       = false;
                            var isUserHasAccess = false;

                            if (qGet.Channel != null)
                            {
                                isBotLock = true;
                                if (isUser.Status == "administrator" || isUser.Status == "member" || isUser.Status == "creator")
                                {
                                    isUserHasAccess = true;
                                }
                            }

                            if (item.Message.Chat.Id == adminId)
                            {
                                mainMenu = new ReplyKeyboardMarkup
                                {
                                    Keyboard = new[] {
                                        new[] { new KeyboardButton("\U000000A9 درباره \U000000A9"), new KeyboardButton("\U00002753 راهنما \U00002753") },
                                        new[] { new KeyboardButton("تنظیمات مدیر \U0001F3E0") }
                                    },
                                    ResizeKeyboard = true
                                };
                            }
                            else
                            {
                                mainMenu = new ReplyKeyboardMarkup
                                {
                                    Keyboard = new[] {
                                        new[] { new KeyboardButton("\U000000A9 درباره \U000000A9"), new KeyboardButton("\U00002753 راهنما \U00002753") },
                                        new[] { new KeyboardButton("\U0001F4DE تماس با ما \U0001F4DE") },
                                    },
                                    ResizeKeyboard = true
                                };
                            }

                            if ((isBotLock && isUserHasAccess) || (isBotLock == false))
                            {
                                if (whatDo == 0)
                                {
                                    switch (userText)
                                    {
                                    case "/start":

                                        var req = new SendMessage(item.Message.Chat.Id, "به ربات پیام رسان خوش آمدید")
                                        {
                                            ReplyMarkup = mainMenu
                                        };

                                        await bot.MakeRequestAsync(req);

                                        break;

                                    //************************************
                                    case string a when a.Contains("خانه"):

                                        req = new SendMessage(item.Message.Chat.Id, "خانه ربات")
                                        {
                                            ReplyMarkup = mainMenu
                                        };

                                        await bot.MakeRequestAsync(req);

                                        break;

                                    //************************************
                                    case string a when a.Contains("تنظیمات مدیر"):

                                        req = new SendMessage(item.Message.Chat.Id, "در این بخش می توانید تنظیمات خود را اعمال کنید")
                                        {
                                            ReplyMarkup = AdminMenu
                                        };

                                        await bot.MakeRequestAsync(req);

                                        break;

                                    //************************************
                                    case string a when a.Contains("درباره"):

                                        req = new SendMessage(item.Message.Chat.Id, "ربات سایت آی ترفند")
                                        {
                                            ReplyMarkup = BackToMain
                                        };

                                        await bot.MakeRequestAsync(req);

                                        break;

                                    //************************************
                                    case string a when a.Contains("راهنما"):

                                        req = new SendMessage(item.Message.Chat.Id, "این روبات برای سایت آی ترفند می باشد \n" +
                                                              " توسط آن می توانید کارهای محتلفی انجام بدهید")
                                        {
                                            ReplyMarkup = BackToMain
                                        };

                                        await bot.MakeRequestAsync(req);

                                        break;

                                    //************************************
                                    case string a when a.Contains("ربات قفل دار"):

                                        if (item.Message.Chat.Id == adminId)
                                        {
                                            req = new SendMessage(item.Message.Chat.Id, "لطفا آدرس کانالی که میخواهید کاربر در صورت عضو بود در آن بتواند از ربات استفاده کند را به همراه @ مانند @itarfand وارد کنید" +
                                                                  "\n\nاگر نمی خواهید کلمه *نه* را وارد کنید")
                                            {
                                                ReplyMarkup = AdminMenu, ParseMode = SendMessage.ParseModeEnum.Markdown
                                            };

                                            await bot.MakeRequestAsync(req);

                                            whatDo = 11;
                                        }
                                        else
                                        {
                                            req = new SendMessage(item.Message.Chat.Id, "شما مدیر نیستید")
                                            {
                                                ReplyMarkup = mainMenu
                                            };

                                            await bot.MakeRequestAsync(req);
                                        }
                                        break;

                                    //************************************
                                    case string a when a.Contains("تماس با ما"):

                                        req = new SendMessage(item.Message.Chat.Id, "لطفا پیغام خود را بفرستید. در اسرع وقت پاسخ داده خواهد شد" +
                                                              "\nنکته: پیغام خود را فقط در این پست بفرستید");

                                        await bot.MakeRequestAsync(req);

                                        whatDo = 12;

                                        break;

                                    //************************************
                                    case string a when a.Contains("پاسخ به پیغام ها"):

                                        if (item.Message.Chat.Id == adminId)
                                        {
                                            req = new SendMessage(item.Message.Chat.Id, "لطفا بر روی پیغام مورد نظر راست کلیک کنید و reply را انتخاب کرده و پیغام خود را بنویسید");

                                            await bot.MakeRequestAsync(req);

                                            whatDo = 20;
                                        }
                                        else
                                        {
                                            req = new SendMessage(item.Message.Chat.Id, "شما مدیر نیستید")
                                            {
                                                ReplyMarkup = mainMenu
                                            };

                                            await bot.MakeRequestAsync(req);
                                        }
                                        break;
                                    }
                                }
                                else
                                {
                                    if (whatDo == 11)
                                    {
                                        var requserText = new SendMessage(item.Message.Chat.Id, userText)
                                        {
                                            ReplyMarkup = AdminMenu
                                        };

                                        await bot.MakeRequestAsync(requserText);

                                        try
                                        {
                                            var qGetLock = (from a in db.Settings
                                                            where a.Id.Equals(1)
                                                            select a).SingleOrDefault();

                                            if (userText.Equals("نه"))
                                            {
                                                qGetLock.Channel = 1235;
                                            }
                                            else
                                            {
                                                qGetLock.Channel = Convert.ToInt64(userText);
                                            }

                                            db.Settings.Attach(qGetLock);
                                            db.Entry(qGetLock).State = System.Data.Entity.EntityState.Modified;
                                            db.SaveChanges();
                                        }
                                        catch (Exception)
                                        {
                                            var req = new SendMessage(item.Message.Chat.Id, "خطا")
                                            {
                                                ReplyMarkup = mainMenu
                                            };

                                            await bot.MakeRequestAsync(req);

                                            continue;
                                        }

                                        whatDo = 0;
                                    }

                                    else if (whatDo == 12)
                                    {
                                        //var requserText = new SendMessage(adminId, from + userText) { ReplyMarkup = mainMenu, ParseMode = SendMessage.ParseModeEnum.Markdown };

                                        var fileId   = item.Message.MessageId;
                                        var fromUser = item.Message.From.Id;
                                        var req2     = new ForwardMessage(adminId, fromUser, fileId);

                                        //await bot.MakeRequestAsync(requserText);
                                        await bot.MakeRequestAsync(req2);

                                        whatDo = 0;
                                    }

                                    else if (whatDo == 20)
                                    {
                                        if (item.Message.ReplyToMessage?.Text != null)
                                        {
                                            var toUser = item.Message.ReplyToMessage.ForwardFrom.Id;

                                            var req2 = new SendMessage(toUser, item.Message.Text);
                                            await bot.MakeRequestAsync(req2);
                                        }

                                        whatDo = 0;
                                    }

                                    else
                                    {
                                        var req3 = new SendMessage(item.Message.Chat.Id, "لطفا ابزار مورد نظر خود را انتخاب کنید")
                                        {
                                            ReplyMarkup = mainMenu
                                        };

                                        await bot.MakeRequestAsync(req3);
                                    }
                                }
                            }
                            else
                            {
                                var req = new SendMessage(item.Message.Chat.Id, "برای استفاده از این ربات ابتدا باید در کانال @itarfand عضو شوید");

                                await bot.MakeRequestAsync(req);
                            }
                        }

                        catch (Exception)
                        {
                            var req = new SendMessage(item.Message.Chat.Id, "خطا")
                            {
                                ReplyMarkup = mainMenu
                            };

                            await bot.MakeRequestAsync(req);

                            whatDo = 0;

                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            // ReSharper disable once FunctionNeverReturns
        }
Ejemplo n.º 18
0
        public async void Run()
        {
            var MainMenu = new ReplyKeyboardMarkup();

            MainMenu.Keyboard = new KeyboardButton[][]
            {
                new KeyboardButton[]
                {
                    new KeyboardButton("About Us👍"),
                },

                new KeyboardButton[]
                {
                    new KeyboardButton("Supported Site for leeching?")
                }
            };
            TelegramBot Bot = null;

            try {
                Bot = new TelegramBot(Token);
                await Bot.MakeRequestAsync(new GetMe());

                log.AddMessage(string.Format("Bot connected."), Log.Type.OutPut);
            }
            catch { log.AddMessage("Can't connect the bot!", Log.Type.Error); return; }
            long Offset = 0;

            while (stat)
            {
                var Update = await Bot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = Offset
                });

                foreach (var Up in Update)
                {
                    try
                    {
                        List <Item> items = new List <Item>();
                        Offset = Up.UpdateId + 1;
                        var    Message = Up.Message.Text;
                        string neh     = "";
                        if (Message != "")
                        {
                            log.AddMessage(string.Format("Telegram Service: Text: {0}  Username: {1} ChatID: {2}", Message, Up.Message.From.Username, Up.Message.From.Id), MSC.Log.Type.Infomation);
                            if (Message == "About Us👍")
                            {
                                neh += @"
💢Bot             By   : Rextor
💢MSC           By   : Rextor
💢Scryipts      By  :  Rextor && Reza-HNA
💢Account    By   : SkyFall

➖➖➖➖➖➖➖➖➖➖
Powered By MSC | @VIPLeechBot";
                                var msg = new SendMessage(Up.Message.Chat.Id, neh)
                                {
                                    ReplyMarkup = MainMenu
                                };
                                await Bot.MakeRequestAsync(msg);
                            }
                            if (Message == "/start")
                            {
                                neh = @"♨️با سلام خدمت کاربر گرامی 
به ربات وی ای پی لیچر (VIP Leecher) خوش امدید 
با استفاده از این ربات میتوانید از سایت های زیر بدون محدودیت دانلود کنید با سرعت زیاد 😃";

                                neh += @"

➖➖➖➖➖➖➖➖➖➖
Powered By MSC | @VIPLeechBot";
                                var msg = new SendMessage(Up.Message.Chat.Id, neh)
                                {
                                    ReplyMarkup = MainMenu
                                };
                                await Bot.MakeRequestAsync(msg);
                            }
                            if (Message == "Supported Site for leeching?")
                            {
                                SiteDetecter.TypeSite[] list = Enum.GetValues(typeof(SiteDetecter.TypeSite)).Cast <SiteDetecter.TypeSite>().ToArray();
                                Array.Sort <SiteDetecter.TypeSite>(list);
                                List <string> lfw = new List <string>();
                                foreach (SiteDetecter.TypeSite item in list)
                                {
                                    lfw.Add(item.ToString());
                                }
                                ArrayList q = new ArrayList();
                                foreach (object o in lfw)
                                {
                                    q.Add(o);
                                }
                                q.Sort();
                                lfw.Clear();
                                foreach (object o in q)
                                {
                                    lfw.Add(o.ToString());
                                }
                                neh += @"💢Supported Site for leeching :
";
                                foreach (string gw in lfw)
                                {
                                    neh += @"
💢" + gw;
                                }


                                neh += @"

➖➖➖➖➖➖➖➖➖➖
Powered By MSC | @VIPLeechBot";
                                var msg = new SendMessage(Up.Message.Chat.Id, neh)
                                {
                                    ReplyMarkup = MainMenu
                                };
                                await Bot.MakeRequestAsync(msg);
                            }

                            else
                            {
                                Leecher.Scripts.SiteDetecter.TypeSite typesite = Scripts.SiteDetecter.GetTypeSite(Message);
                                neh = typesite.ToString() + @" Detected!
Please wait...";
                                var msg = new SendMessage(Up.Message.Chat.Id, neh)
                                {
                                    ReplyMarkup = MainMenu
                                };
                                await Bot.MakeRequestAsync(msg);

                                string url = Message;

                                items = Core.GetList(url, "", typesite);

                                neh = @"🚀Links:

";
                                foreach (Item i in items)
                                {
                                    neh += @"
➖➖➖➖➖➖➖➖➖➖
📌" + i.Info + @"
📂" + i.Link;
                                }


                                neh += @"

➖➖➖➖➖➖➖➖➖➖
Powered By MSC | @VIPLeechBot";
                                if (items.Count != 0)
                                {
                                    var msg1 = new SendMessage(Up.Message.Chat.Id, neh)
                                    {
                                        ReplyMarkup = MainMenu
                                    };
                                    await Bot.MakeRequestAsync(msg1);
                                }
                            }
                        }
                    }
                    catch (Exception ex) { log.AddMessage(ex.Message, Log.Type.Error); }
                }
            }
        }
Ejemplo n.º 19
0
 public async Task SendMessageReadAsync(ReceiveMessage receiveMessage)
 {
     var sendMessage = new SendMessage(receiveMessage.MessageId, receiveMessage.SenderId, UserId, receiveMessage.ReceiverType, MessageType.readStatusChange, "");
     await WebSocketClient.SendMassage(Newtonsoft.Json.JsonConvert.SerializeObject(sendMessage));
 }
Ejemplo n.º 20
0
 protected bool Equals(SendMessage other)
 {
     return Message == other.Message && string.Equals(Data, other.Data);
 }
Ejemplo n.º 21
0
 /// <summary>
 /// 发送消息
 /// </summary>
 /// <param name="receiveId">接收者ID</param>
 /// <param name="receiverType">接收者类别</param>
 /// <param name="messageType">消息类别</param>
 /// <param name="message">消息</param>
 /// <returns></returns>
 public async Task SendMessageAsync(Guid receiveId, ReceiverType receiverType, MessageType messageType, string message)
 {
     var sendMessage = new SendMessage(Guid.NewGuid(), UserId, receiveId, receiverType, messageType, message);
     await WebSocketClient.SendMassage(Newtonsoft.Json.JsonConvert.SerializeObject(sendMessage));
 }
        public async Task<Result> CreatePost(string messageUserId, string post,
            UserAuthenticationEntity userAuthenticationEntity, string region = "jp")
        {
            var url = string.Format(EndPoints.CreatePost, region, messageUserId);
            const string boundary = "gc0p4Jq0M2Yt08jU534c0p";
            var messageJson = new SendMessage
            {
                message = new Message()
                {
                    body = post,
                    fakeMessageUid = 1234,
                    messageKind = 1
                }
            };

            var json = JsonConvert.SerializeObject(messageJson);
            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
            stringContent.Headers.Add("Content-Description", "message");
            var form = new MultipartContent("mixed", boundary) { stringContent };
            return await _webManager.PostData(new Uri(url), form, userAuthenticationEntity);
        }
Ejemplo n.º 23
0
 public static string SendMesageing(string mobile, string ran)
 {
     SendMessage.SendMobileVerification(mobile, ran, "90");
     return("1");
 }
        public async Task<Result> CreateStickerPost(string messageUserId, string manifestFileUrl, string number,
            string imageUrl, string packageId, string type, UserAuthenticationEntity userAuthenticationEntity,
            string region = "jp")
        {
            var url = string.Format(EndPoints.CreatePost, region, messageUserId);
            const string boundary = "gc0p4Jq0M2Yt08jU534c0p";
            var messageJson = new SendMessage
            {
                message = new Message()
                {
                    body = string.Empty,
                    fakeMessageUid = 1234,
                    messageKind = 1013,
                    stickerDetail = new StickerDetail()
                    {
                        imageUrl = imageUrl,
                        manifestFileUrl = manifestFileUrl,
                        number = number,
                        packageId = packageId,
                        type = type
                    }
                }
            };

            var json = JsonConvert.SerializeObject(messageJson);
            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
            stringContent.Headers.Add("Content-Description", "message");
            var form = new MultipartContent("mixed", boundary) { stringContent };
            return await _webManager.PostData(new Uri(url), form, userAuthenticationEntity);
        }
Ejemplo n.º 25
0
 public Form2()
 {
     InitializeComponent();
     Sender = new SendMessage(GetMessage);
 }
Ejemplo n.º 26
0
 public DangNhap( SendMessage sender, SendMessage1 sender1)
 {
     InitializeComponent();
     this.send = sender;
     this.send1 = sender1;
 }
Ejemplo n.º 27
0
        public static async Task RunBot()
        {
            List <Users> BotDataList = new List <Users>();
            var          bot         = new TelegramBot(Token);
            var          me          = await bot.MakeRequestAsync(new GetMe());

            Console.WriteLine("UserName Is: {0} And My Name Is {1}", me.Username, me.FirstName);
            var User = new User();

            Console.WriteLine(User.Id);
            long offset     = 0;
            int  whilecount = 0;

            while (true)
            {
                Console.WriteLine("WhileCount is:{0} ", whilecount);
                whilecount++;
                var Updates = await bot.MakeRequestAsync(new GetUpdates()
                {
                    Offset = offset
                });

                Console.WriteLine("Update Count Is:{0}", Updates.Count());
                Console.WriteLine("--------------------------------------------");
                try
                {
                    foreach (var Update in Updates)
                    {
                        offset = Update.UpdateId++;
                        var text = Update.Message.Text;
                        if (text == "/start")
                        {
                            var req = new SendMessage(Update.Message.Chat.Id, "لطفا یک گزینه انتخاب کنید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(req);

                            continue;
                        }
                        else if (text != null && text.Contains("شروع بازی جدید"))
                        {
                            var Message1 = new SendMessage(Update.Message.Chat.Id, "سیستم درحال حدس عدد.")
                            {
                                ReplyMarkup = new ReplyKeyboardRemove()
                                {
                                    RemoveKeyboard = true
                                }
                            };
                            await bot.MakeRequestAsync(Message1);

                            Users NewUser = new Users(me.FirstName + me.LastName, me.Id, 0);
                            RandomGenerator(ref NewUser.ComputerGuess);
                            var Message2 = new SendMessage(Update.Message.Chat.Id, "حدس عدد انجام شد.");
                            await bot.MakeRequestAsync(Message2);

                            var Message3 = new SendMessage(Update.Message.Chat.Id, "لطفا یک عدد 4 رقمی حدس بزنید.");
                            await bot.MakeRequestAsync(Message3);

                            NewUser.Counter = 5;
                            while (NewUser.Counter > 0)
                            {
                                offset = Update.UpdateId++;
                                var Guess = Update.Message.Text;
                                try
                                {
                                    if (Guess != null && Guess.Contains(NewUser.ComputerGuess))
                                    {
                                        var Message4 = new SendMessage(Update.Message.Chat.Id, "درست حدس زدید.");
                                        await bot.MakeRequestAsync(Message4);

                                        NewUser.Score += 5;
                                        var Message5 = new SendMessage(Update.Message.Chat.Id, "امتیاز شما:" + NewUser.Score);
                                        await bot.MakeRequestAsync(Message5);

                                        NewUser.Counter = 0;
                                        continue;
                                    }
                                    else if (Guess != null)
                                    {
                                        var Message4 = new SendMessage(Update.Message.Chat.Id, GuessTrueOrFalse(NewUser.ComputerGuess, Guess));
                                        await bot.MakeRequestAsync(Message4);

                                        continue;
                                    }
                                    else if (NewUser.Counter == 0)
                                    {
                                        var Message4 = new SendMessage(Update.Message.Chat.Id, GuessTrueOrFalse(NewUser.ComputerGuess, Guess));
                                        await bot.MakeRequestAsync(Message4);
                                    }
                                    NewUser.Counter--;
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);
                                    var Message4 = new SendMessage(Update.Message.Chat.Id, "لطفا عدد وارد کنید.");
                                    continue;
                                }
                            }
                        }
                        else if (text != null && text.Contains("امتیاز شما"))
                        {
                            var req = new SendMessage(Update.Message.Chat.Id, "درحال توسعه.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(req);

                            continue;
                        }
                        else if (text != null && text.Contains("برترین بازیکنان"))
                        {
                            var req = new SendMessage(Update.Message.Chat.Id, "درحال توسعه.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(req);

                            continue;
                        }
                        else if (text != null && text.Contains("درباره ی ما"))
                        {
                        }
                        else
                        {
                            var req = new SendMessage(Update.Message.Chat.Id, "لطفا یک گزینه انتخاب کنید.")
                            {
                                ReplyMarkup = MainMenu
                            };
                            await bot.MakeRequestAsync(req);

                            continue;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    throw;
                }
            }
        }
 public FrmDoiThongTinNhanVien()
 {
     InitializeComponent();
     //Tạo con trỏ tới hàm GetMessage
     Sender = new SendMessage(GetMessage);
 }
Ejemplo n.º 29
0
 public RealTimeSample(SocketClient client, CancellationToken cancel)
 {
     //_file = new SendFile(client.Output, LogAsync.Instance.Filename);
     _client = new SendMessage(client.Output);
     _cancel = cancel;
 }
Ejemplo n.º 30
0
 void When(SendMessage e)
 {
     Then(new MessageReceived(e.Message, e.User));
 }
 /// <summary>
 /// Get creative by creative name.
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public DMCreative GetCreative(string name)
 {
     return(SendMessage
            .GetAllCreatives(Token)
            .SingleOrDefault(a => a.Name.ToLower() == name.ToLower()));
 }
Ejemplo n.º 32
0
 public CT_PhieuNhap()
 {
     InitializeComponent();
     Sender = new SendMessage(GetMessage);
 }
Ejemplo n.º 33
0
 public void sendmessage(string msg)
 {
     SendMessage SMessage = new SendMessage();
     SMessage.message = msg;
     SMessage.sender = UserName;
     SendIMessage(SMessage);
 }
Ejemplo n.º 34
0
        public void GetDecision(MessageEventArgs e, SendMessage send)
        {
            JsonConverter[] c = new JsonConverter[1];
            c[0] = new Newtonsoft.Json.Converters.StringEnumConverter();
            string   data = e.Data;
            IMessage m    = Deserialize <IMessage>(data, c);

            switch (m.Type)
            {
            case MessageType.AddBookRequest:
                HandleAddBookRequest(send, Deserialize <AddBookRequest>(data, c));
                break;

            case MessageType.CheckoutRequest:
                HandleCheckoutRequest(send, Deserialize <CheckoutRequest>(data, c));
                break;

            case MessageType.CreateUserRequest:
                HandleCreateUserRequest(send, Deserialize <CreateUserRequest>(data, c));
                break;

            case MessageType.GetBookRequest:
                HandleGetBookRequest(send, Deserialize <GetBookRequest>(data, c));
                break;

            case MessageType.LoginRequest:
                HandleLoginRequest(send, Deserialize <LoginRequest>(data, c));
                break;

            case MessageType.RenewalRequest:
                HandleRenewalRequest(send, Deserialize <RenewalRequest>(data, c));
                break;

            case MessageType.ResetPasswordRequest:
                HandleResetPasswordRequest(send, Deserialize <ResetPasswordRequest>(data, c));
                break;

            case MessageType.RetireBookRequest:
                HandleRetireBookRequest(send, Deserialize <RetireBookRequest>(data, c));
                break;

            case MessageType.ReturnRequest:
                HandleReturnRequest(send, Deserialize <ReturnRequest>(data, c));
                break;

            case MessageType.SearchBookRequest:
                DecideSearchBookRequest(send, Deserialize <SearchBookRequest>(data, c));
                break;

            case MessageType.UpdateBookConditionRequest:
                HandleUpdateBookConditionRequest(send, Deserialize <UpdateBookConditionRequest>(data, c));
                break;

            case MessageType.ViewCheckedoutRequest:
                HandleViewCheckedoutRequest(send, Deserialize <ViewCheckedoutRequest>(data, c));
                break;

            default:
                break;
            }
        }
Ejemplo n.º 35
0
 public AntiFlood(string ServerName)
 {
     sMyChannelInfo = sIrcBase.Networks[ServerName].sMyChannelInfo;
     sSendMessage = sIrcBase.Networks[ServerName].sSendMessage;
 }
Ejemplo n.º 36
0
 internal static void Resend(SendMessage ToSend)
 {
     //WaitAck.TryAdd(long.Parse(ToSend.MessageId), ToSend);
     Send((object)ToSend);
 }
Ejemplo n.º 37
0
 public SendMessage AddMessage(SendMessage message)
 {
     NextMessage = message;
     return this;
 }
 public frmKhoiTaoNgauNhien(SendMessage _sender)
 {
     InitializeComponent();
     this.SenderData = _sender;
 }
Ejemplo n.º 39
0
        public async Task<Result> CreatePostWithMedia(string messageUserId, string post, string path, byte[] fileStream,
            UserAuthenticationEntity userAuthenticationEntity, string region = "jp")
        {
            var url = string.Format(EndPoints.CreatePost, region, messageUserId);
            const string boundary = "abcdefghijklmnopqrstuvwxyz";
            var messageJson = new SendMessage
            {
                message = new Message()
                {
                    body = post,
                    fakeMessageUid = 1445225905274,
                    messageKind = 3
                }
            };

            var json = JsonConvert.SerializeObject(messageJson);
            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
            stringContent.Headers.Add("Content-Description", "message");
            var form = new MultipartContent("mixed", boundary) { stringContent };

            Stream stream = new MemoryStream(fileStream);
            var t = new StreamContent(stream);
            var s = Path.GetExtension(path);
            if (s != null && s.Equals(".png"))
            {
                t.Headers.ContentType = new MediaTypeHeaderValue("image/png");
            }
            else
            {
                var extension = Path.GetExtension(path);
                if (extension != null && (extension.Equals(".jpg") || extension.Equals(".jpeg")))
                {
                    t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                }
                else
                {
                    t.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
                }
            }
            t.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            t.Headers.Add("Content-Description", "image-data-0");
            t.Headers.Add("Content-Transfer-Encoding", "binary");
            t.Headers.ContentLength = stream.Length;
            form.Add(t);

            return await _webManager.PostData(new Uri(url), form, userAuthenticationEntity);
        }
Ejemplo n.º 40
0
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            text = textbox[(uint)(myTabControl1.SelectedTab.Tag)].Text;
            textbox[(uint)(myTabControl1.SelectedTab.Tag)].Text = "";

            if (!string.IsNullOrEmpty(text.Trim())) // Если textBox не пустой, то печатаем сообщение в richTextBox, а затем отправляем
            {
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionStart = richtbox[Convert.ToUInt32(myTabControl1.SelectedTab.Tag)].Text.Length;
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionLength = 0;
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionFont = new Font(FontFamily.GenericSerif, 8, FontStyle.Bold);
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionColor = Color.FromArgb(0, 0, 255);

                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectedText = "Я (" + DateTime.Now.ToShortTimeString() + " " + DateTime.Now.ToShortDateString() + ")";
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionStart = richtbox[(uint)(myTabControl1.SelectedTab.Tag)].Text.Length;
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionLength = 0;
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionFont = new Font(FontFamily.GenericSerif, 9, FontStyle.Regular);
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionColor = Color.Black;
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectedText = "\r\n" + text + "\r\n";
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionStart = richtbox[(uint)(myTabControl1.SelectedTab.Tag)].Text.Length;
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionLength = 0;
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectionFont = new Font(FontFamily.GenericSerif, 4, FontStyle.Regular);
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].SelectedText = "\r\n";
                richtbox[(uint)(myTabControl1.SelectedTab.Tag)].ScrollToCaret();

                if (vars.VARS.Out_message_on && vars.VARS.Sound)
                    GeneralMethods.NotifySound("OutMessage");
            }

            vk start = new vk();

            SendMessage SendMsg = new SendMessage(start.sendMsg);
            IAsyncResult res1 = SendMsg.BeginInvoke(text, (uint)myTabControl1.SelectedTab.Tag, null, null);

            res1.AsyncWaitHandle.WaitOne();

            bool success = SendMsg.EndInvoke(res1);

            if (!success)
            {
                NotifyEvent ShowNotify = new NotifyEvent(ShowNotifyWindow);
                this.Invoke(ShowNotify, "Ошибка!", "Ошибка при отправке!\nПовторите ещё раз!", (uint)0);
            }
        }
Ejemplo n.º 41
0
        /// <summary>
        /// 返回结果,直接写入数据库(alarm,alarm_log,line)
        /// </summary>
        /// <param name="id">线路Id</param>
        /// <param name="pingState"></param>
        public void WriteAlarmToDB(int id, PingState pingState)
        {
            lock (_lock)
            {
                try
                {
                    if (!_catch.ContainsKey(id))
                    {
                        _catch.Add(id, new LineAlarmCache()
                        {
                            Alarm = null, Count = 0
                        });
                    }

                    if (!pingState.State)
                    {
                        _catch[id].Count++;
                        if (_catch[id].Alarm == null)
                        {
                            LineModel line = new LineBusiness().GetItem(id);
                            if (_catch[id].Count >= line.AlarmMax)
                            {
                                _catch[id].Alarm = new AlarmModel()
                                {
                                    AlarmCount = 1,
                                    Confirm    = false,
                                    FirstTime  = pingState.CollectTime,
                                    IP         = line.LineIP,
                                    LineId     = line.Id,
                                    LineName   = line.Name,
                                    OrganId    = line.OrganizationId,
                                    OrganName  = line.OrganizationName,
                                    State      = AlarmStateType.OnAlarm,
                                    LastTime   = pingState.CollectTime,
                                    Type       = AlarmType.LineNotConnected
                                };
                                //状态改为 正在告警
                                MonitorADOProvider.GetInstance().InsertAlarm(_catch[id].Alarm);
                                SendMessage?.Invoke(_catch[id].Alarm, line.SMSTelphone);
                            }
                        }
                        else
                        {
                            if (_catch[id].Alarm.Id == 0)
                            {
                                _catch[id].Alarm = MonitorADOProvider.GetInstance().GetLastestAlarm(id, AlarmType.LineNotConnected);
                            }
                            //更新次数和最后时间
                            MonitorADOProvider.GetInstance().UpdateAlarm(_catch[id].Alarm.Id, pingState.CollectTime);
                        }
                    }
                    else
                    {
                        if (_catch[id].Alarm != null)
                        {
                            if (_catch[id].Alarm.Id == 0)
                            {
                                _catch[id].Alarm = MonitorADOProvider.GetInstance().GetLastestAlarm(id, AlarmType.LineNotConnected);
                            }
                            LineModel line = MonitorADOProvider.GetInstance().GetLineModel(id);
                            MonitorADOProvider.GetInstance().RecoverAlarm(_catch[id].Alarm.Id, DateTime.Now, AlarmStateType.Recover);
                            SendMessage?.Invoke(_catch[id].Alarm, line.SMSTelphone);
                        }
                    }



                    //var alarm = _catch[id].Provider.GetLastestAlarm(id, AlarmType.LineNotConnected);
                    //if (!pingState.State)
                    //{
                    //    _catch[id].Count++;

                    //    //根据告警策略 更新 告警状态
                    //    if (alarm == null)
                    //    {
                    //        LineModel line = new LineBusiness().GetItem(id);
                    //        //肯定是有alarm的
                    //        if (_catch[id].Count >= line.AlarmMax)
                    //        {
                    //            alarm = new AlarmModel()
                    //            {
                    //                AlarmCount = 1,
                    //                Confirm = false,
                    //                FirstTime = pingState.CollectTime,
                    //                IP = line.LineIP,
                    //                LineId = line.Id,
                    //                LineName = line.Name,
                    //                OrganId = line.OrganizationId,
                    //                OrganName = line.OrganizationName,
                    //                State = AlarmStateType.OnAlarm,
                    //                LastTime = pingState.CollectTime,
                    //                Type = AlarmType.LineNotConnected
                    //            };
                    //            //状态改为 正在告警
                    //            _catch[id].Provider.InsertSync(alarm);
                    //            SendMessage?.Invoke(alarm, line.SMSTelphone);
                    //        }
                    //    }
                    //    else
                    //    {
                    //        //更新次数和最后时间
                    //        string condition = "AND Id = @Id";
                    //        string field = "AlarmCount=@AlarmCount,LastTime=@LastTime";
                    //        _catch[id].Provider.UpdateSync(condition, field, new { Id = alarm.Id, AlarmCount = alarm.AlarmCount + 1, LastTime = pingState.CollectTime });
                    //    }
                    //}
                    //else
                    //{
                    //    if (alarm != null)
                    //    {
                    //        LineModel line = new LineBusiness().GetItem(id);
                    //        alarm.RecoverDate = pingState.CollectTime;
                    //        alarm.State = AlarmStateType.Recover;
                    //        //alarm.AlarmCount = _catch[id].Count;
                    //        _catch[id].Provider.AddRecoverDate(alarm);
                    //        SendMessage?.Invoke(alarm, line.SMSTelphone);
                    //    }
                    //}
                }
                catch (Exception ex)
                {
                }
            }
        }
Ejemplo n.º 42
0
 private void OnSendMessage(Message m)
 {
     SendMessage?.Invoke(this, new SendMessageEventArgs(m));
 }
Ejemplo n.º 43
0
        //Anonymous methods
        public static void TestingAnonymousFunc()
        {
            SendMessage anonymousFunc = name => Console.WriteLine("This is the msj here : " + name);

            anonymousFunc("Anonymous");
        }
Ejemplo n.º 44
0
        public static void RunBot(string accessToken)
        {
            var bot = new TelegramBot(accessToken);

            var me = bot.MakeRequestAsync(new GetMe()).Result;
            if (me == null)
            {
                Console.WriteLine("GetMe() FAILED. Do you forget to add your AccessToken to App.config?");
                Console.WriteLine("(Press ENTER to quit)");
            }
            Console.WriteLine("{0} (@{1}) connected!", me.FirstName, me.Username);

            Console.WriteLine();
            Console.WriteLine("Find @{0} in Telegram and send him a message - it will be displayed here", me.Username);
            Console.WriteLine("(Press ENTER to stop listening and quit)");
            Console.WriteLine();

            string uploadedPhotoId = null;
            string uploadedDocumentId = null;
            long offset = 0;
            while (!stopMe)
            {
                var updates = bot.MakeRequestAsync(new GetUpdates() { Offset = offset }).Result;
                if (updates != null)
                {
                    foreach (var update in updates)
                    {
                        offset = update.UpdateId + 1;
                        if (update.Message == null)
                        {
                            continue;
                        }
                        var from = update.Message.From;
                        var text = update.Message.Text;
                        Console.WriteLine(
                            "Msg from {0} {1} ({2}) at {4}: {3}",
                            from.FirstName,
                            from.LastName,
                            from.Username,
                            text,
                            update.Message.Date);

                        if (string.IsNullOrEmpty(text))
                        {
                            continue;
                        }
                        if (text == "/photo")
                        {
                            if (uploadedPhotoId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_photo");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var photoData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.t_logo.png"))
                                {
                                    var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(photoData, "Telegram_logo.png"))
                                    {
                                        Caption = "Telegram_logo.png"
                                    };
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedPhotoId = msg.Photo.Last().FileId;
                                }
                            }
                            else
                            {
                                var req = new SendPhoto(update.Message.Chat.Id, new FileToSend(uploadedPhotoId))
                                {
                                    Caption = "Resending photo id=" + uploadedPhotoId
                                };
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/doc")
                        {
                            if (uploadedDocumentId == null)
                            {
                                var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                                bot.MakeRequestAsync(reqAction).Wait();
                                System.Threading.Thread.Sleep(500);
                                using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Telegram_Bot_API.htm"))
                                {
                                    var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Telegram_Bot_API.htm"));
                                    var msg = bot.MakeRequestAsync(req).Result;
                                    uploadedDocumentId = msg.Document.FileId;
                                }
                            }
                            else
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(uploadedDocumentId));
                                bot.MakeRequestAsync(req).Wait();
                            }
                            continue;
                        }
                        if (text == "/docutf8")
                        {
                            var reqAction = new SendChatAction(update.Message.Chat.Id, "upload_document");
                            bot.MakeRequestAsync(reqAction).Wait();
                            System.Threading.Thread.Sleep(500);
                            using (var docData = Assembly.GetExecutingAssembly().GetManifestResourceStream("TelegramBotDemo.Пример UTF8 filename.txt"))
                            {
                                var req = new SendDocument(update.Message.Chat.Id, new FileToSend(docData, "Пример UTF8 filename.txt"));
                                var msg = bot.MakeRequestAsync(req).Result;
                                uploadedDocumentId = msg.Document.FileId;
                            }
                            continue;
                        }
                        if (text == "/help")
                        {
                            var keyb = new ReplyKeyboardMarkup()
                            {
                                Keyboard = new[] { new[] { "/photo", "/doc", "/docutf8" }, new[] { "/help" } },
                                OneTimeKeyboard = true,
                                ResizeKeyboard = true
                            };
                            var reqAction = new SendMessage(update.Message.Chat.Id, "Here is all my commands") { ReplyMarkup = keyb };
                            bot.MakeRequestAsync(reqAction).Wait();
                            continue;
                        }
                        if (update.Message.Text.Length % 2 == 0)
                        {
                            bot.MakeRequestAsync(new SendMessage(update.Message.Chat.Id, "You wrote " + update.Message.Text.Length + " characters")).Wait();
                        }
                        else
                        {
                            bot.MakeRequestAsync(new ForwardMessage(update.Message.Chat.Id, update.Message.Chat.Id, update.Message.MessageId)).Wait();
                        }
                    }
                }
            }
        }
Ejemplo n.º 45
0
 public async Task SendMessage <T>(SendMessage <T> message) where T : class, new()
 {
     Loger.LogMessage("发送命令:" + JsonHelper.SerializeObj(message));
     await TcpHelper.SendMessage(message, _client);
 }
        public async Task<Result> CreatePostWithMedia(string messageUserId, string post, string path, Stream stream,
            UserAuthenticationEntity userAuthenticationEntity, string region = "jp")
        {
            var url = string.Format(EndPoints.CreatePost, region, messageUserId);
            const string boundary = "gc0p4Jq0M2Yt08jU534c0p";
            var messageJson = new SendMessage
            {
                message = new Message()
                {
                    body = post,
                    fakeMessageUid = 1234,
                    messageKind = 3
                }
            };

            var json = JsonConvert.SerializeObject(messageJson);
            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
            stringContent.Headers.Add("Content-Description", "message");
            var form = new MultipartContent("mixed", boundary) { stringContent };
            var t = new StreamContent(stream);
            t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            t.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            t.Headers.Add("Content-Description", "image-data-0");
            t.Headers.Add("Content-Transfer-Encoding", "binary");
            t.Headers.ContentLength = stream.Length;
            form.Add(t);

            return await _webManager.PostData(new Uri(url), form, userAuthenticationEntity);
        }
Ejemplo n.º 47
0
 /**
  * onMyTradeEvent
  *
  * @param param    param
  */
 public abstract void onMyTradeEvent(SendMessage sendMessage);
        public async Task<Result> CreateNewGroupMessage(string[] toArray, string message, UserAuthenticationEntity currentTokens, string region)
        {
            var url = string.Format(EndPoints.CreateNewGroupPost, region);
            const string boundary = "gc0p4Jq0M2Yt08jU534c0p";
            var messageJson = new SendMessage
            {
                to = toArray,
                message = new Message()
                {
                    body = message,
                    fakeMessageUid = 1234,
                    messageKind = 1
                }
            };

            var json = JsonConvert.SerializeObject(messageJson);
            var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
            stringContent.Headers.Add("Content-Description", "message");
            var form = new MultipartContent("mixed", boundary) { stringContent };
            return await _webManager.PostData(new Uri(url), form, currentTokens, "ja", true);
        }
Ejemplo n.º 49
0
 /**
  * onMyOrderEvent
  *
  * @param param    param
  */
 public abstract void onMyOrderEvent(SendMessage send);
        public FrmHoaDonNhap()
        {
            InitializeComponent();

            Sender = new SendMessage(GetMessage);
        }
Ejemplo n.º 51
0
 protected internal override void OnReceiveMessage(bool bIsSystemError, string nMessageCode, string szMessage)
 {
     base.OnReceiveMessage(bIsSystemError, nMessageCode, szMessage);
     SendMessage?.Invoke(this, new NotifyIconText(szMessage));
 }
Ejemplo n.º 52
0
        public async Task<bool> CreatePostWithMedia(string messageUserId, string post, String path, byte[] fileStream,
            UserAccountEntity userAccountEntity)
        {
            try
            {
                var user = userAccountEntity.GetUserEntity();
                var url = string.Format(EndPoints.CreatePost, user.Region, messageUserId);
                const string boundary = "abcdefghijklmnopqrstuvwxyz";
                var messageJson = new SendMessage
                {
                    message = new Message()
                    {
                        body = post,
                        fakeMessageUid = 1384958573288,
                        messageKind = 1
                    }
                };

                var json = JsonConvert.SerializeObject(messageJson);
                var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
                stringContent.Headers.Add("Content-Description", "message");
                var form = new MultipartContent("mixed", boundary) { stringContent };

                Stream stream = new MemoryStream(fileStream);
                var t = new StreamContent(stream);
                var s = Path.GetExtension(path);
                if (s != null && s.Equals(".png"))
                {
                    t.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                }
                else
                {
                    var extension = Path.GetExtension(path);
                    if (extension != null && (extension.Equals(".jpg") || extension.Equals(".jpeg")))
                    {
                        t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                    }
                    else
                    {
                        t.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
                    }
                }
                t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                t.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                t.Headers.Add("Content-Description", "image-data-0");
                t.Headers.Add("Content-Transfer-Encoding", "binary");
                t.Headers.ContentLength = stream.Length;
                form.Add(t);

                var result = await _webManager.PostData(new Uri(url), form, null, userAccountEntity);
                return result.IsSuccess;
            }
            catch (Exception ex)
            {

                throw new Exception("Failed to send post (with media)", ex);
            }
        }
Ejemplo n.º 53
0
 public void InitializeCommandHandler()
 {
     sSendMessage = new SendMessage(_servername);
     sIgnoreChannel = new IgnoreChannel(_servername);
     sSender = new Sender(_servername);
     sMyNickInfo = new MyNickInfo(_servername);
     sIgnoreAddon = new IgnoreAddon(_servername);
     sIgnoreCommand = new IgnoreCommand(_servername);
     sIgnoreNickName = new IgnoreNickName(_servername);
     sIgnoreIrcCommand = new IgnoreIrcCommand(_servername);
     sMyChannelInfo = new MyChannelInfo(_servername);
     sIrcLog = new IrcLog(_servername);
     sAntiFlood = new AntiFlood(_servername);
     sCtcpSender = new CtcpSender(_servername);
     sChannelList = new ChannelList(_servername);
 }