Prevent page load every time on Whatsapp Automation using selenium- C# - c#

I am developing a automation of Whatsapp using silenium and C# with web whatsapp for my personal reason.
I am currently stuck in 2 problems
My number get blocked on sending message where as i had already places delay of 10-15 seconds in each request.
Each time my page reload on whastapp call i need to prevent it and want to place message directly any way for it ?
Note- numbers are dynamic and coming from DB.
Code
private void msgnew(string number, string message, int len, string oldnumber)
{
driver.Navigate().GoToUrl("https://web.whatsapp.com/send?phone=" + number + "&text=" + Uri.EscapeDataString(message) + "&lang=en&app_absent=1");
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
driver.FindElement(By.CssSelector("button._4sWnG>span")).Click();//Click SEND Arrow Button
}

you can do it in js as:
js = """
var [ num ] = [ arguments[0]];
function openChat (t) {
var e;
t&&((e=document.createElement("a")).setAttribute("href","whatsapp://send?phone="+t),document.body.appendChild(e),e.click(),e.outerHTML="",setTimeout(1,1e3))
}
return openChat(num)
"""
now use ExecuteScript ,
in python :
js = """
var [ num ] = [ arguments[0]];
function openChat (t) {
var e;
t&&((e=document.createElement("a")).setAttribute("href","whatsapp://send?phone="+t),document.body.appendChild(e),e.click(),e.outerHTML="",setTimeout(1,1e3))
}
return openChat(num)
"""
self.driver.execute_script(js, number)
and to check if current number opened:
js = """
var [ t ] = [ arguments[0]];
if (document.querySelectorAll(`[data-id*="${t}#"]`).length > 0 || (document.querySelector(`#main header span[title]`) && document.querySelector(`#main header span[title]`).title.replace(/\s/g, '').replace('-', '').replace('+','').replace('⁩', '').replace('⁦', '') == t)
){
return true
}
"""
r = self.driver.execute_script(js, number)
r will be true if open current number.

Related

Exit Chat Window When Finished In Unity

I'm trying to build an interface so I can load a chat window with
messages I can read in the window. The user presses enter and the message index is incremented
so the next message is displayed. After the last message is displayed for
e.g. lvl 7, event 1 I would like the window to close.
The 3 parameters are the level, event, messageindex.
What happens is I don't see the chat window and no messages are
displayed in the window. How can i modify the algorithm so
that I read all the messages for the level and event and then
the window closes properly?
...
Debug.Log("File size is" + sizeoffile);
for (int i = 0; i < sizeoffile; i++)
{
if ((storyitemData["storyline"][i]["event"].ToString() == eventno.ToString()) & (storyitemData["storyline"][i]["level"].ToString() == levelno.ToString()) & (storyitemData["storyline"][i]["index"].ToString() == msgindex.ToString()))
{
Debug.Log("read message was called with message index " + msgindex + " and the content is " + storyitemData["storyline"][i]["content"].ToString());
//check that this is right
txtlbl.GetComponent<Text>().text = storyitemData["storyline"][i]["content"].ToString();
}
else if ((storyitemData["storyline"][i]["event"].ToString() == eventno.ToString()) & (storyitemData["storyline"][i]["level"].ToString() == levelno.ToString()) & (storyitemData["storyline"][i]["index"].ToString() != msgindex.ToString()))
{
msgindex = 1;
chatwindow.active = false;
}
}
Example JSON
{
"storyline":[
{
"level":1,
"event":1,
"index":1,
"content":"hello"
},
{
"level":1,
"event":1,
"index":2,
"content":"yes I saw that"
},
{
"level":7,
"event":1,
"index":1,
"content":"can I buy a sandwhich?"
},
{
"level":7,
"event":1,
"index":2,
"content":"thank you"
},
{
"level":7,
"event":1,
"index":3,
"content":"Salt please"
},
{
"level":7,
"event":2,
"index":1,
"content":"Java was"
},
{
"level":7,
"event":2,
"index":2,
"content":"my first language"
}
]
}
There are numerous ways you can handle this and without more code is hard to determine exactly what your setup is. All you have really shown us is that you are passing in a specific index to the list but for some reason still iterating over a list with a size of sizeoffile which is not mentioned at all.
I am also not sure if you intended this, but in your if conditionals, you are not using a && AND operator, but a bit-wise & AND operator, which is different.
You can simply add another conditional check first to see if the current index you are reading is about to exceed the container type you are using.
if((storyitemData["storyline"].Count) <= msgindex)
{
// we reached the end of the container, so disable our chat window
}
else if((storyitemData["storyline"][i]["event"].ToString() == eventno.ToString()) & (storyitemData["storyline"][i]["level"].ToString() == levelno.ToString()) & (storyitemData["storyline"][i]["index"].ToString() == msgindex.ToString())))
{
...
}
If what I have mentioned does not work, please add more detail to your question, and a bit more code would not hurt either. Adding the original container of the structure you are serializing to JSON would help. Is there a reason you are serializing an entire chat log to JSON to pass around your game?

MQCMD_INQUIRE_Q_STATUS, PCF command returns "Unknown type" exception

I'm using the following code for returning handles of a queue, if the queue does not have any handle (open input/output count would be 0) it return MQRCCF_Q_STATUS_NOT_FOUND but when it has some open handle, it returns "Unknown type" exception.
public void getQueue(string Name)
{
PCFMessage reqeuestMessage = new PCFMessage(MQC.MQCMD_INQUIRE_Q_STATUS);
reqeuestMessage.AddParameter(MQC.MQCA_Q_NAME, Name);
reqeuestMessage.AddParameter(CMQCFC.MQIACF_Q_STATUS_TYPE, CMQCFC.MQIACF_Q_HANDLE);
PCFMessage[] response = agent.Send(reqeuestMessage);
foreach (PCFMessage st in response)
{
...
}
}
MQ PCF support in C# is limited , so it may not support some parameters. It's possible that the parameter that you are trying to inquire is not in the list of supported parameters. Please note MQ PCF in .NET is not officially supported by IBM MQ.
If your intention is to inquire the number of applications have opened a queue for input & output, you can use the INQUIRE_Q command and filter out input/output count. Sample snippet is here:
PCFMessage reqeuestMessage = new PCFMessage(MQC.MQCMD_INQUIRE_Q);
reqeuestMessage.AddParameter(MQC.MQCA_Q_NAME, "Q1");
// Send request and receive response
PCFMessage[] pcfResponse = messageAgent.Send(reqeuestMessage);
// Process and print response.
int pcfResponseLen = pcfResponse.Length;
for (int pcfResponseIdx = 0; pcfResponseIdx < pcfResponseLen; pcfResponseIdx++)
{
PCFParameter[] parameters = pcfResponse[pcfResponseIdx].GetParameters();
foreach (PCFParameter pm in parameters)
{
// We just want to print current queue depth only
if ((pm.Parameter == MQC.MQIA_OPEN_OUTPUT_COUNT) || (pm.Parameter == MQC.MQIA_OPEN_INPUT_COUNT))
Console.WriteLine("Parameter: " + pm.Parameter + " - Value: " + pm.GetValue());
}
}
Hope this helped

Calling My REST API Using C#

I'm trying to call my own REST API that returns JSON using a simple C# GUI application, and am looking for the simplest way to do so:
http://danielmiessler.com:44821/token/dGVxdWllcm8=
I am opening a file containing tokens and reading the contents line by line to get the final part of the URL:
StreamReader input = new StreamReader(openFileDialog1.OpenFile());
while ((line = input.ReadLine()) != null) {
This is going back into a textbox:
textBox2.Text += ("\t" + result + "\r\n");
Here is the Ruby code I'm trying to reproduce:
# Get our libraries
require 'httparty'
require 'json'
# Get our input from the command line
input = ARGV[0]
# Loop through the file
File.open("#{input}", "r").each_line do |line|
# Request the URL
response = HTTParty.get("http://danielmiessler.com:44821/token/#{line.chomp}")
# Go through the responses
case response.code
when 400
print "Improper input…\n"
# Feel free to remove this line if you want to reduce output.
when 200
json = JSON.parse(response.body)
print "Your input is #{json['type']} of the word: #{json['value']}\n"
when 404
print "There is no meaning in your token…\n"
# Feel free to remove this line if you want to reduce output.
end
end
Any ideas how to make the calls based on the tokens in the file and output to the text box?
You can use HttpClient for that.
This is a minimal example to get you started:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.GetAsync(_address).ContinueWith(
(requestTask) =>
{
HttpResponseMessage response = requestTask.Result;
response.EnsureSuccessStatusCode();
response.Content.ReadAsAsync<JsonArray>().ContinueWith(
(readTask) =>
{
Console.WriteLine(
"First 50 countries listed by The World Bank...");
foreach (var country in readTask.Result[1])
{
Console.WriteLine(" {0}, Country Code: {1}, " +
"Capital: {2}, Latitude: {3}, Longitude: {4}",
country.Value["name"],
country.Value["iso2Code"],
country.Value["capitalCity"],
country.Value["latitude"],
country.Value["longitude"]);
}
});
});
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}

Sending Multipart PDU SMS by AT Command

I have successfully sent a multipart pdu sms,
The problem is when i try to send this SMS to a number on a different network it gives me the following error :
+CMGS ERROR:500
Please can any one tell me what should i do.
atCommandStr = "AT+CMGF=0\r";
comPort.WriteLine(atCommandStr + (char)13);
Console.WriteLine(comPort.ReadExisting());
Thread.Sleep(2000);
for (int i = 0; i < number_of_parts; i++)
{
int oct = (messagesParts[i].ToCharArray().Count() / 2) -1;
atCommandStr = "AT+CMGS=" + oct + "\r";
comPort.WriteLine(atCommandStr + (char)13);
Console.WriteLine(comPort.ReadExisting());
Thread.Sleep(2000);
string path;
path = messagesParts[i] + Char.ConvertFromUtf32(26);
comPort.WriteLine(path + (char)13);
for (int a = 0; a < 100; a++)
{
Thread.Sleep(2000);
string t = comPort.ReadExisting();
Console.WriteLine(t);
if (t != "" && t.Contains("CMGS") || t.Contains("ERROR"))
{
break;
}
}
//Console.WriteLine(comPort.ReadExisting());
}
Did the modem really return +CMGS ERROR:500 and not +CMS ERROR: 500? Because in that case, your modem is not compliant with the 27.005 standard which specifies if sending fails: +CMS ERROR: <err>.
Error code 500 means unknown error, so that does not help very much. But I would guess that your length calculation is wrong. From the standard:
<length> must indicate the number of octets coded in the TP layer data unit
to be given (i.e. SMSC address octets are excluded).
Is it correct to subtract 1 after dividing by 2? Try to decode exactly what will be sent on TP layer. Try to increase/decrease the length a bit and see if it makes any difference.
Also, since atCommandStr already contains \r you should not include the + (char)13 in
comPort.WriteLine(atCommandStr + (char)13);

jQuery post request is not sent until first post request is completed

I have a function which have a long execution time.
public void updateCampaign()
{
context.Session[processId] = "0|Fetching Lead360 Campaign";
Lead360 objLead360 = new Lead360();
string campaignXML = objLead360.getCampaigns();
string todayDate = DateTime.Now.ToString("dd-MMMM-yyyy");
context.Session[processId] = "1|Creating File for Lead360 Campaign on " + todayDate;
string fileName = HttpContext.Current.Server.MapPath("campaigns") + todayDate + ".xml";
objLead360.createFile(fileName, campaignXML);
context.Session[processId] = "2|Reading The latest Lead360 Campaign";
string file = File.ReadAllText(fileName);
context.Session[processId] = "3|Updating Lead360 Campaign";
string updateStatus = objLead360.updateCampaign(fileName);
string[] statusArr = updateStatus.Split('|');
context.Session[processId] = "99|" + statusArr[0] + " New Inserted , " + statusArr[1] + " Updated , With " + statusArr[2] + " Error , ";
}
So to track the Progress of the function I wrote a another function
public void getProgress()
{
if (context.Session[processId] == null)
{
string json = "{\"error\":true}";
Response.Write(json);
Response.End();
}else{
string[] status = context.Session[processId].ToString().Split('|');
if (status[0] == "99") context.Session.Remove(processId);
string json = "{\"error\":false,\"statuscode\":" + status[0] + ",\"statusmsz\":\"" + status[1] + "\" }";
Response.Write(json);
Response.End();
}
}
To call this by jQuery post request is used
reqUrl = "AjaxPages/lead360Campaign.aspx?processid=" + progressID + "&action=updatecampaign";
$.post(reqUrl);
setTimeout(getProgress, 500);
get getProgress is :
function getProgress() {
reqUrl = "AjaxPages/lead360Campaign.aspx?processid=" + progressID + "&action=getProgress";
$.post(reqUrl, function (response) {
var progress = jQuery.parseJSON(response);
console.log(progress)
if (progress.error) {
$("#fetchedCampaign .waitingMsz").html("Some error occured. Please try again later.");
$("#fetchedCampaign .waitingMsz").css({ "background": "url(common/images/ajax_error.jpg) no-repeat center 6px" });
return;
}
if (progress.statuscode == 99) {
$("#fetchedCampaign .waitingMsz").html("Update Status :"+ progress.statusmsz );
$("#fetchedCampaign .waitingMsz").css({ "background": "url(common/images/ajax_loded.jpg) no-repeat center 6px" });
return;
}
$("#fetchedCampaign .waitingMsz").html("Please Wait... " + progress.statusmsz);
setTimeout(getProgress, 500);
});
}
But the problem is that I can't see the intermediate message. Only the last message is been displayed after a long lime of ajax loading message
Also on the browser console I just see that after a long time first requested is completed and after that the second request is completed. but there should be for getProgress ?
I have checked jquery.doc and it says that $post is an asynchronous request.
Can anyone please explain what is wrong with the code or logic?
You are in a situation discussed here:
ASP.net session request queuing
While a request for a given user's session is processed, other requests for the same session are waiting. You need to run your long function in a background thread and let the request that initiates it finish. However, the background thread will not have access to session, and you will need a different mechanism to communicate its progress.
From the information you've provided, I would suspect that it's not your javascript code that's being synchronous, but rather the server-side code. You can test this by using Firebug or Chrome's dev tools to look at the start and end times of the two AJAX requests. If I'm right, you'll see that the second request begins after half a second, but doesn't complete until after the first one.
If that's the case, possible causes are:
Running in a dev environment in Visual Studio, especially in debug mode, seems to reduce the amount of asynchronicity. The dev environment seems to like to process one request at a time.
See Igor's answer about session request queueing.
You may have code that explicitly locks resources and causes the second request to block until the long-running request is done.
One other possible culprit is the fact that most browsers only allow a limited number of concurrent requests to a particular domain. If you have a few requests pending at any given moment, the browser may just be queuing up the remaining requests until they return.

Categories

Resources