Speech Recognition windows 10 - c#

I'm trying to build a speech recognition in Windows 10 (using Cortana) in Visual C#.
This is part of my code for speech recognition using old System.Speech.Recognition and works great, but it only support english.
SpeechSynthesizer sSynth = new SpeechSynthesizer();
PromptBuilder pBuilder = new PromptBuilder();
SpeechRecognitionEngine sRecognize = new SpeechRecognitionEngine();
Choices sList = new Choices();
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
pBuilder.ClearContent();
pBuilder.AppendText(textBox2.Text);
sSynth.Speak(pBuilder);
}
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
button3.Enabled = true;
sList.Add(new string[] { "who are you", "play a song" });
Grammar gr = new Grammar(new GrammarBuilder(sList));
try
{
sRecognize.RequestRecognizerUpdate();
sRecognize.LoadGrammar(gr);
sRecognize.SpeechRecognized += sRecognize_SpeechRecognized;
sRecognize.SetInputToDefaultAudioDevice();
sRecognize.RecognizeAsync(RecognizeMode.Multiple);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
private void sRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
textBox1.Text = textBox1.Text + " " + e.Result.Text.ToString() + "\r\n";
}
How can I do it using new speech recognition in windows 10?

Use Microsoft Speech Platform SDK v11.0 (Microsoft.Speech.Recognition).
It works like System.Speech, but you can use Italian language (separeted install) and also use SRGS Grammar. I work with both kinect (SetInputToAudioStream) and default input device (SetInputToDefaultAudioDevice) without hassle.
Also it works offline, so no need to be online as with Cortana.
With the SRGS grammar you can get a decent level of complexity for your commands
UPDATE
Here is how I initialize the recognizer
private RecognizerInfo GetRecognizer(string culture, string recognizerId)
{
try
{
foreach (var recognizer in SpeechRecognitionEngine.InstalledRecognizers())
{
if (!culture.Equals(recognizer.Culture.Name, StringComparison.OrdinalIgnoreCase)) continue;
if (!string.IsNullOrWhiteSpace(recognizerId))
{
string value;
recognizer.AdditionalInfo.TryGetValue(recognizerId, out value);
if ("true".Equals(value, StringComparison.OrdinalIgnoreCase))
return recognizer;
}
else
return recognizer;
}
}
catch (Exception e)
{
log.Error(m => m("Recognizer not found"), e);
}
return null;
}
private void InitializeSpeechRecognizer(string culture, string recognizerId, Func<Stream> audioStream)
{
log.Debug(x => x("Initializing SpeechRecognizer..."));
try
{
var recognizerInfo = GetRecognizer(culture, recognizerId);
if (recognizerInfo != null)
{
recognizer = new SpeechRecognitionEngine(recognizerInfo.Id);
//recognizer.LoadGrammar(VoiceCommands.GetCommandsGrammar(recognizerInfo.Culture));
recognizer.LoadGrammar(grammar);
recognizer.SpeechRecognized += SpeechRecognized;
recognizer.SpeechRecognitionRejected += SpeechRejected;
if (audioStream == null)
{
log.Debug(x => x("...input on DefaultAudioDevice"));
recognizer.SetInputToDefaultAudioDevice();
}
else
{
log.Debug(x => x("SpeechRecognizer input on CustomAudioStream"));
recognizer.SetInputToAudioStream(audioStream(), new SpeechAudioFormatInfo(EncodingFormat.Pcm, 16000, 16, 1, 32000, 2, null));
}
}
else
{
log.Error(x => x(Properties.Resources.SpeechRecognizerNotFound, recognizerId));
throw new Exception(string.Format(Properties.Resources.SpeechRecognizerNotFound, recognizerId));
}
log.Debug(x => x("...complete"));
}
catch (Exception e)
{
log.Error(m => m("Error while initializing SpeechEngine"), e);
throw;
}
}

Cortana API usage example is here. You can copy it and start modifying according to your needs. It creates a dialog with the user. You can not exactly reproduce your System.Speech code with Cortana API because it is designed for another purpose. If you still want to recognize just few words, you can continue using System.Speech API.
System.Speech API supports other languages, not just English. You can find more information here:
Change the language of Speech Recognition Engine library

Related

SAPI does not implement phonetic alphabet selection. Speech Command App

In my speech command app, I am loading files from an external source, processing that data and loading them into a list of possible commands for execution
When I run the app, I get the message in the console
Main.exe Information: 0: SAPI does not implement phonetic alphabet selection.
I tried solutions such as adding
gram.Culture = New System.Globalization.CultureInfo("en-GB")
I think this is either outdated or does not work on this type of WPF application
Any tips?
Code:
{
InitializeComponent();
}
SpeechSynthesizer synth = new SpeechSynthesizer();
PromptBuilder builder = new PromptBuilder();
SpeechRecognitionEngine recog = new SpeechRecognitionEngine();
private System.Windows.Input.Key k;
private int vkey;
private Choices cmd;
private void Button_Click_1(object sender, RoutedEventArgs e)
{
b1.IsEnabled = false;
Choices list = new Choices();
cmd = Singleton.getInstance().getChoices();
list.Add(new string[] { "hello", "test", "it works", "sup", "windows", "grenade" });
Grammar gr = new Grammar(new GrammarBuilder(cmd));
try
{
recog.RequestRecognizerUpdate();
recog.LoadGrammar(gr);
recog.SpeechRecognized += Recog_SpeechRecognized;
recog.SetInputToDefaultAudioDevice();
recog.RecognizeAsync(RecognizeMode.Multiple);
}
catch
{
return;
}
}

How to convert speech to text?

I am trying to develop the following functionality.
The first task to convert text to voice - DONE
The second task to convert voice to text - Getting issue
The third task to implement these both on the given chat board where already AI chat is
I am using following code to get the text from voice/speech.
I am getting the result but is not proper which I want.
Please check below code snippet.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Speech.Recognition;
using System.Speech.Synthesis;
namespace StartingWithSpeechRecognition
{
class Program
{
static SpeechRecognitionEngine _recognizer = null;
static ManualResetEvent manualResetEvent = null;
static void Main(string[] args)
{
manualResetEvent = new ManualResetEvent(false);
Console.WriteLine("To recognize speech, and write 'test' to the console, press 0");
Console.WriteLine("To recognize speech and make sure the computer speaks to you, press 1");
Console.WriteLine("To emulate speech recognition, press 2");
Console.WriteLine("To recognize speech using Choices and GrammarBuilder.Append, press 3");
Console.WriteLine("To recognize speech using a DictationGrammar, press 4");
Console.WriteLine("To get a prompt building example, press 5");
ConsoleKeyInfo pressedKey = Console.ReadKey(true);
char keychar = pressedKey.KeyChar;
Console.WriteLine("You pressed '{0}'", keychar);
switch (keychar)
{
case '0':
RecognizeSpeechAndWriteToConsole();
break;
case '1':
RecognizeSpeechAndMakeSureTheComputerSpeaksToYou();
break;
case '2':
EmulateRecognize();
break;
case '3':
SpeechRecognitionWithChoices();
break;
case '4':
SpeechRecognitionWithDictationGrammar();
break;
case '5':
PromptBuilding();
break;
default:
Console.WriteLine("You didn't press 0, 1, 2, 3, 4, or 5!");
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey(true);
Environment.Exit(0);
break;
}
if (keychar != '5')
{
manualResetEvent.WaitOne();
}
if (_recognizer != null)
{
_recognizer.Dispose();
}
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey(true);
}
#region Recognize speech and write to console
static void RecognizeSpeechAndWriteToConsole()
{
_recognizer = new SpeechRecognitionEngine();
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder("test"))); // load a "test" grammar
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder("exit"))); // load a "exit" grammar
_recognizer.SpeechRecognized += _recognizeSpeechAndWriteToConsole_SpeechRecognized; // if speech is recognized, call the specified method
_recognizer.SpeechRecognitionRejected += _recognizeSpeechAndWriteToConsole_SpeechRecognitionRejected; // if recognized speech is rejected, call the specified method
_recognizer.SetInputToDefaultAudioDevice(); // set the input to the default audio device
_recognizer.RecognizeAsync(RecognizeMode.Multiple); // recognize speech asynchronous
}
static void _recognizeSpeechAndWriteToConsole_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (e.Result.Text == "test")
{
Console.WriteLine("test");
}
else if (e.Result.Text == "exit")
{
manualResetEvent.Set();
}
}
static void _recognizeSpeechAndWriteToConsole_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
Console.WriteLine("Speech rejected. Did you mean:");
foreach (RecognizedPhrase r in e.Result.Alternates)
{
Console.WriteLine(" " + r.Text);
}
}
#endregion
#region Recognize speech and make sure the computer speaks to you (text to speech)
static void RecognizeSpeechAndMakeSureTheComputerSpeaksToYou()
{
_recognizer = new SpeechRecognitionEngine();
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder("hello computer"))); // load a "hello computer" grammar
_recognizer.SpeechRecognized += _recognizeSpeechAndMakeSureTheComputerSpeaksToYou_SpeechRecognized; // if speech is recognized, call the specified method
_recognizer.SpeechRecognitionRejected += _recognizeSpeechAndMakeSureTheComputerSpeaksToYou_SpeechRecognitionRejected;
_recognizer.SetInputToDefaultAudioDevice(); // set the input to the default audio device
_recognizer.RecognizeAsync(RecognizeMode.Multiple); // recognize speech asynchronous
}
static void _recognizeSpeechAndMakeSureTheComputerSpeaksToYou_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (e.Result.Text == "hello computer")
{
SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
speechSynthesizer.Speak("hello user");
speechSynthesizer.Dispose();
}
manualResetEvent.Set();
}
static void _recognizeSpeechAndMakeSureTheComputerSpeaksToYou_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
{
if (e.Result.Alternates.Count == 0)
{
Console.WriteLine("No candidate phrases found.");
return;
}
Console.WriteLine("Speech rejected. Did you mean:");
foreach (RecognizedPhrase r in e.Result.Alternates)
{
Console.WriteLine(" " + r.Text);
}
}
#endregion
#region Emulate speech recognition
static void EmulateRecognize()
{
_recognizer = new SpeechRecognitionEngine();
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder("emulate speech"))); // load "emulate speech" grammar
_recognizer.SpeechRecognized += _emulateRecognize_SpeechRecognized;
_recognizer.EmulateRecognize("emulate speech");
}
static void _emulateRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (e.Result.Text == "emulate speech")
{
Console.WriteLine("Speech was emulated!");
}
manualResetEvent.Set();
}
#endregion
#region Speech recognition with Choices and GrammarBuilder.Append
static void SpeechRecognitionWithChoices()
{
_recognizer = new SpeechRecognitionEngine();
GrammarBuilder grammarBuilder = new GrammarBuilder();
grammarBuilder.Append("I"); // add "I"
grammarBuilder.Append(new Choices("like", "dislike")); // load "like" & "dislike"
grammarBuilder.Append(new Choices("dogs", "cats", "birds", "snakes", "fishes", "tigers", "lions", "snails", "elephants")); // add animals
_recognizer.LoadGrammar(new Grammar(grammarBuilder)); // load grammar
_recognizer.SpeechRecognized += speechRecognitionWithChoices_SpeechRecognized;
_recognizer.SetInputToDefaultAudioDevice(); // set input to default audio device
_recognizer.RecognizeAsync(RecognizeMode.Multiple); // recognize speech
}
static void speechRecognitionWithChoices_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
Console.WriteLine("Do you really " + e.Result.Words[1].Text + " " + e.Result.Words[2].Text + "?");
manualResetEvent.Set();
}
#endregion
#region Speech recognition with DictationGrammar
static void SpeechRecognitionWithDictationGrammar()
{
_recognizer = new SpeechRecognitionEngine();
_recognizer.LoadGrammar(new Grammar(new GrammarBuilder("exit")));
_recognizer.LoadGrammar(new DictationGrammar());
_recognizer.SpeechRecognized += speechRecognitionWithDictationGrammar_SpeechRecognized;
_recognizer.SetInputToDefaultAudioDevice();
_recognizer.RecognizeAsync(RecognizeMode.Multiple);
}
static void speechRecognitionWithDictationGrammar_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (e.Result.Text == "exit")
{
manualResetEvent.Set();
return;
}
Console.WriteLine("You said: " + e.Result.Text);
}
#endregion
#region Prompt building
static void PromptBuilding()
{
PromptBuilder builder = new PromptBuilder();
builder.StartSentence();
builder.AppendText("This is a prompt building example.");
builder.EndSentence();
builder.StartSentence();
builder.AppendText("Now, there will be a break of 2 seconds.");
builder.EndSentence();
builder.AppendBreak(new TimeSpan(0, 0, 2));
builder.StartStyle(new PromptStyle(PromptVolume.ExtraSoft));
builder.AppendText("This text is spoken extra soft.");
builder.EndStyle();
builder.StartStyle(new PromptStyle(PromptRate.Fast));
builder.AppendText("This text is spoken fast.");
builder.EndStyle();
SpeechSynthesizer synthesizer = new SpeechSynthesizer();
synthesizer.Speak(builder);
synthesizer.Dispose();
}
#endregion
}
}
If this is the wrong way then please suggest me right way or any reference link or tutorial will be highly appreciated.
The System.Speech.Recognition is an old API.
I think you have to use Google Speech API: https://cloud.google.com/speech/docs/basics Or MS Bing speech API: https://azure.microsoft.com/en-us/services/cognitive-services/speech/
I preferred the Google API. And here is very small example:
using Google.Apis.Auth.OAuth2;
using Google.Cloud.Speech.V1;
using Grpc.Auth;
using System;
var speech = SpeechClient.Create( channel );
var response = speech.Recognize( new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRateHertz = 16000,
LanguageCode = "hu",
}, RecognitionAudio.FromFile( "888.wav" ) );
foreach ( var result in response.Results )
{
foreach ( var alternative in result.Alternatives )
{
Console.WriteLine( alternative.Transcript );
}
}
But you can find more samples:
https://cloud.google.com/speech/docs/samples
Regrads

Unable to Call Events using Zkemkeeper SDK

I am facing trouble in calling events in Zkemkeeper.dll. I have succesfully established the connection however on putting the finger on sensor no event is fired. Infact no realtime event is being triggered.
Any help would be appreciated following is my code;
private void button2_Click(object sender, EventArgs e)
{
string s = "";
int Val = 0;
bool bIsConnected = false;
try {
//zkemkeeper.CZKEMClass axczkem1 = new zkemkeeper.CZKEMClass();
// bIsConnected = axczkem1.Connect_USB(1);
bIsConnected = axczkem1.Connect_Com(6,1,115200);
if(bIsConnected==true){
Cursor = Cursors.Default;
bool asa= axczkem1.EnableDevice(1, true);
if (axczkem1.RegEvent(1, 65535))
{
axczkem1.OnFinger += new zkemkeeper._IZKEMEvents_OnFingerEventHandler(axczkem1_OnFinger);
axczkem1.OnKeyPress += new zkemkeeper._IZKEMEvents_OnKeyPressEventHandler(axczkem1_OnKeyPress);
axczkem1.OnConnected += new _IZKEMEvents_OnConnectedEventHandler(axCZKEM1_OnConnected);
axczkem1.OnVerify += new zkemkeeper._IZKEMEvents_OnVerifyEventHandler(axCZKEM1_OnVerify);
}
MessageBox.Show("Connection established!!!");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
And following are the event methods:
private void axCZKEM1_OnVerify(int UserID)
{
label2.Text = "Verify";
}
private void axCZKEM1_OnConnected()
{
label1.Text = "Connected";
}
private void axczkem1_OnKeyPress(int Key)
{
MessageBox.Show(Key.ToString());
}
private void axczkem1_OnFinger()
{
MessageBox.Show("Connection");
}
if this is a windows form application . If program have long running process event doesn't work . For example loop (while,for) . And also Thread.sleep() .
If you want to trigger work your program do nothing .
If this is not a windows form see this link enter link description here

c# - Record audio on keydown

The problem is simple: I want to record audio using the microphone when and only when a key is held down. When the key is lifted I want it to stop recording. Then pass this recording to the speech recognition.
The issue is when I press and hold the Z button, It will go into the gkh_KeyUp event and continue to run this code. I want to simply record while it is held, not run this record function a bunch of times.
I want to use this in conjunction with Microsofts speech recognition.
using System.Speech.Recognition;
public partial class Form1 : Form
{
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
Grammar dictationGrammar = new DictationGrammar();
public Form1()
{
InitializeComponent();
globalKeyboardHook gkh = new globalKeyboardHook();
gkh.HookedKeys.Add(Keys.Z);
//gkh.HookedKeys.Add(Keys.B);
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
recognizer = new SpeechRecognitionEngine();
dictationGrammar = new DictationGrammar();
recognizer.LoadGrammar(dictationGrammar);
}
void gkh_KeyUp(object sender, KeyEventArgs e)
{
textBox1.Text = "Up" + e.KeyCode.ToString();
try
{
RecognitionResult result = recognizer.Recognize();
textBox1.Text = result.Text;
}
catch (InvalidOperationException exception)
{
textBox1.Text = String.Format("Could not recognize input from default aduio device. Is a microphone or sound card available?\r\n{0} - {1}.", exception.Source, exception.Message);
}
e.Handled = true;
}
void gkh_KeyDown(object sender, KeyEventArgs e)
{
textBox1.Text += "Down" + e.KeyCode.ToString();
try
{
//recognizer.SetInputToDefaultAudioDevice();
recognizer.SetInputToAudioStream()
}
catch (InvalidOperationException exception)
{
button1.Text = String.Format("Could not recognize input from default aduio device. Is a microphone or sound card available?\r\n{0} - {1}.", exception.Source, exception.Message);
}
e.Handled = true;
}
private void button1_Click(object sender, EventArgs e)
{
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
Grammar dictationGrammar = new DictationGrammar();
recognizer.LoadGrammar(dictationGrammar);
try
{
button1.Text = "Speak Now";
recognizer.SetInputToDefaultAudioDevice();
//recognizer.SetInputToAudioStream;
RecognitionResult result = recognizer.Recognize();
textBox1.Text = result.Text;
}
catch (InvalidOperationException exception)
{
button1.Text = String.Format("Could not recognize input from default aduio device. Is a microphone or sound card available?\r\n{0} - {1}.", exception.Source, exception.Message);
}
finally
{
recognizer.UnloadAllGrammars();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
Keyboard hook: http://www.codeproject.com/Articles/19004/A-Simple-C-Global-Low-Level-Keyboard-Hook
There is no difference between real very frequent keypresses and keypresses emulated when you hold the button.
You'd need to use a timeout, if the down was not emitted after 0.5 seconds after up, you stop the recording.
You can access hold state of the key if you still want to use a hook, but you need to use a bit lower level access. You can explore WM_KEYDOWN event and look for a bit 30 of the key state:
How to disable WM_KEYDOWN repeat event for Shift/Ctrl/Alt key?

MSNP-Sharp Example fails to login, gives SocketException

I've just downloaded the MSNP-Sharp library with the aim of creating my own messaging client, however I am struggling to get the example to sign in. The code all compiles and runs, but when I provide my login details and select "Login" I almost immediately get the following SocketException:
"No connection could be made because the target machine actively refused it 64.4.9.254:1863"
I've stepped through the code and it's the messenger.Connect() function that is causing this, somewhat obviously. When I run the example I only change the login and password details. I am running Windows 7 x86 with the latest version of Windows Live Messenger.
I have tried disabling my antivirus, even going as far as to temporarily uninstall it in case that was the error.
I have also tried disabling Windows Firewall, with no luck.
Firstly, use the stable version of MSNPSharp (that is, 3.0). Since it is a SocketException, this may relate to a problem within the internet protocol (a firewall for instance). Try to ensure that nothing is blocking the program from accessing to the MSN protocol. Since you have said you have disabled your Windows Firewall, could there be anything else that could be blocking it?
Secondly, have you tried using MSN Messenger Live for a test. If that works, MSNPSharp client should probably work too. Ensure you have .NET Framework 2.0 or within their version of the .NET Framework. If it constantly appears to be a problem, I don't believe this is a problem from the MSNPSharp client (I'm not sure however).
here is a demo,i hope it would be useful
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Color;
namespace MSNRobot
{
using MSNPSharp;
using MSNPSharp.Core;
using MSNPSharp.DataTransfer;
class RobotConversation
{
private Conversation _conversation = null;
private RobotMain _robotmain = null;
public RobotConversation(Conversation conv, RobotMain robotmain)
{
Console.WriteLine("==> Struct a conversation");
_conversation = conv;
_conversation.Switchboard.TextMessageReceived += new EventHandler<TextMessageEventArgs>(Switchboard_TextMessageReceived);
_conversation.Switchboard.SessionClosed += new EventHandler<EventArgs>(Switchboard_SessionClosed);
_conversation.Switchboard.ContactLeft += new EventHandler<ContactEventArgs>(Switchboard_ContactLeft);
_robotmain = robotmain;
}
//online status
private void Switchboard_TextMessageReceived(object sender, TextMessageEventArgs e)
{
Console.WriteLine("==>Received Msg From " + e.Sender.Mail + " Content:\n" + e.Message.Text);
//echo back ///////////// TODO /////////////////
_conversation.Switchboard.SendTextMessage(e.Message);
}
private void Switchboard_SessionClosed(object sender, EventArgs e)
{
Console.WriteLine("==>Session Closed, Remove conversation");
_conversation.Switchboard.Close();
_conversation = null;
_robotmain.RobotConvlist.Remove(this);
}
private void Switchboard_ContactLeft(object sender, ContactEventArgs e)
{
Console.WriteLine("==>Contact Left.");
}
}
class RobotMain
{
private Messenger messenger = new Messenger();
private List<RobotConversation> _convs = new List<RobotConversation>(0);
public RobotMain()
{
messenger.NameserverProcessor.ConnectionEstablished += new EventHandler<EventArgs>(NameserverProcessor_ConnectionEstablished);
messenger.Nameserver.SignedIn += new EventHandler<EventArgs>(Nameserver_SignedIn);
messenger.Nameserver.SignedOff += new EventHandler<SignedOffEventArgs>(Nameserver_SignedOff);
messenger.NameserverProcessor.ConnectingException += new EventHandler<ExceptionEventArgs>(NameserverProcessor_ConnectingException);
messenger.Nameserver.ExceptionOccurred += new EventHandler<ExceptionEventArgs>(Nameserver_ExceptionOccurred);
messenger.Nameserver.AuthenticationError += new EventHandler<ExceptionEventArgs>(Nameserver_AuthenticationError);
messenger.Nameserver.ServerErrorReceived += new EventHandler<MSNErrorEventArgs>(Nameserver_ServerErrorReceived);
messenger.Nameserver.ContactService.ReverseAdded += new EventHandler<ContactEventArgs>(Nameserver_ReverseAdded);
messenger.ConversationCreated += new EventHandler<ConversationCreatedEventArgs>(messenger_ConversationCreated);
messenger.Nameserver.OIMService.OIMReceived += new EventHandler<OIMReceivedEventArgs>(Nameserver_OIMReceived);
messenger.Nameserver.OIMService.OIMSendCompleted += new EventHandler<OIMSendCompletedEventArgs>(OIMService_OIMSendCompleted);
}
public List<RobotConversation> RobotConvlist
{
get
{
return _convs;
}
}
private void NameserverProcessor_ConnectionEstablished(object sender, EventArgs e)
{
//messenger.Nameserver.AutoSynchronize = true;
Console.WriteLine("==>Connection established!");
}
private void Nameserver_SignedIn(object sender, EventArgs e)
{
messenger.Owner.Status = PresenceStatus.Online;
Console.WriteLine("==>Signed into the messenger network as " + messenger.Owner.Name);
}
private void Nameserver_SignedOff(object sender, SignedOffEventArgs e)
{
Console.WriteLine("==>Signed off from the messenger network");
}
private void NameserverProcessor_ConnectingException(object sender, ExceptionEventArgs e)
{
//MessageBox.Show(e.Exception.ToString(), "Connecting exception");
Console.WriteLine("==>Connecting failed");
}
private void Nameserver_ExceptionOccurred(object sender, ExceptionEventArgs e)
{
// ignore the unauthorized exception, since we're handling that error in another method.
if (e.Exception is UnauthorizedException)
return;
Console.WriteLine("==>Nameserver exception:" + e.Exception.ToString());
}
private void Nameserver_AuthenticationError(object sender, ExceptionEventArgs e)
{
Console.WriteLine("==>Authentication failed:" + e.Exception.InnerException.Message);
}
private void Nameserver_ServerErrorReceived(object sender, MSNErrorEventArgs e)
{
// when the MSN server sends an error code we want to be notified.
Console.WriteLine("==>Server error received:" + e.MSNError.ToString());
}
void Nameserver_ReverseAdded(object sender, ContactEventArgs e)
{
//Contact contact = e.Contact;
//contact.OnAllowedList = true;
//contact.OnPendingList = false;
//messenger.Nameserver.ContactService.AddNewContact(contact.Mail);
Console.WriteLine("==>ReverseAdded contact mail:" + e.Contact.Mail);
//messenger.Nameserver.AddNewContact(
e.Contact.OnAllowedList = true;
e.Contact.OnForwardList = true;
}
private void messenger_ConversationCreated(object sender, ConversationCreatedEventArgs e)
{
Console.WriteLine("==>Conversation created");
_convs.Add(new RobotConversation(e.Conversation, this));
}
//offline status
void Nameserver_OIMReceived(object sender, OIMReceivedEventArgs e)
{
Console.WriteLine("==>OIM received at : " + e.ReceivedTime + " From : " +
e.NickName + " (" + e.Email + ") " + e.Message);
TextMessage message = new TextMessage(e.Message);
message.Font = "Trebuchet MS";
//message.Color = Color.Brown;
message.Decorations = TextDecorations.Bold;
Console.WriteLine("==>Echo back");
messenger.OIMService.SendOIMMessage(e.Email, message.Text);
}
void OIMService_OIMSendCompleted(object sender, OIMSendCompletedEventArgs e)
{
if (e.Error != null)
{
Console.WriteLine("OIM Send Error:" + e.Error.Message);
}
}
public void BeginLogin(string account, string password)
{
if (messenger.Connected)
{
Console.WriteLine("==>Disconnecting from server");
messenger.Disconnect();
}
// set the credentials, this is ofcourse something every MSNPSharp program will need to implement.
messenger.Credentials = new Credentials(account, password, MsnProtocol.MSNP16);
// inform the user what is happening and try to connecto to the messenger network.
Console.WriteLine("==>Connecting to server...");
messenger.Connect();
//displayImageBox.Image = global::MSNPSharpClient.Properties.Resources.loading;
//loginButton.Tag = 1;
//loginButton.Text = "Cancel";
// note that Messenger.Connect() will run in a seperate thread and return immediately.
// it will fire events that informs you about the status of the connection attempt.
// these events are registered in the constructor.
}
/// <summary>
/// main()
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
string robot_acc = "";
string robot_passwd = "";
if (args.Length == 0)
{
Console.WriteLine("USAGE:MSNRobot.exe <msn_account> [password]");
return;
}
robot_acc = args[0];
if (args.Length == 2)
robot_passwd = args[1];
else
{
Console.WriteLine("Password for " + robot_acc + ":");
robot_passwd = Console.ReadLine();
}
RobotMain app = new RobotMain();
app.BeginLogin(robot_acc, robot_passwd);
while (true)
{
Console.WriteLine("I am a MSN robot:" + robot_acc);
Console.ReadLine();
}
}
}
}
Have you tried the example client for MSNPSharp?

Categories

Resources