Discord.NET C# Change Content of SocketMessage - c#

So I am listening to the event whenever anyone on the server sends a message to any text channel with my bot. I want to detect swear words like "fuck" and change it to "f*ck".
I was unable to replace my message just normally only with reflection but it did not help since it only replaced it in the instance of the SocketMessage but it did not change the message on the server.
Any solution for that?
Framework: 4.6
Discord.NET: 1.0.2
Code:
private async Task MsgRec(SocketMessage e)
{
try
{
if (e.Content.Contains("fuck"))
{
foreach(PropertyInfo info in typeof(SocketMessage).GetProperties())
{
if (info.Name == "Content")
{
info.SetValue(e,e.Content.Replace("fuck", "f*ck"));
}
}
}
}
catch (Exception ex)
{
await e.Author.SendMessageAsync(ex.StackTrace);
}
}
Update I also tried this without any success:
var rMessage = (RestUserMessage) await e.Channel.GetMessageAsync(e.Id);
await rMessage.ModifyAsync(msg => msg.Content = e.Content.Replace("fuck", "f*ck"));

Discord, like other chat programs, does not allow you to change messages of users. You can not censor what a user wrote, you can only delete the whole message.

maybe you could try something like this
private async Task MsgRec(SocketMessage e)
{
var msg = e as SocketUserMessage;
if (msg == null) return;
if (msg.Content.Contains("fuck"))
{
var newMsg = msg.Content.Replace("fuck", "f*ck");
await Context.Channel.SendMessageAsync(newMsg);
}
}

Related

Write to Bluetooth LE Characteristic as a Server in WPF or UWP

I want to write into a Bluetooth LE Characteristic. (wpf c#, but has to work with UWP also)
I'm not exactly sure how this works, because I want to write a value not as a client, but as the server.
Like in the MS Example:
https://github.com/microsoft/Windows-universal-samples/blob/main/Samples/BluetoothLE/cs/Scenario3_ServerForeground.xaml.cs
The BLE service and characteristic are created on program start. (not in the MS example, but in my program)
After creating a Characteristic
GattLocalCharacteristicResult result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.ModeCharacteristicUuid, Constants.modeParameters);
modeCharacteristic = result.Characteristic;
modeCharacteristic.WriteRequested += ModeCharacteristic_WriteRequestedAsync;
I want to use this method to write into the characteristic:
private async void ModeCharacteristic_WriteRequestedAsync(GattLocalCharacteristic sender, GattWriteRequestedEventArgs args)
{
using (args.GetDeferral())
{
GattWriteRequest request = await args.GetRequestAsync();
if (request == null)
{
// No access allowed to the device. Application should indicate this to the user.
return;
}
request.Respond();
}
}
Only question to me now is how to write in the Mode-Characteristic.
For example, I simply want to write a 5 into this Characteristic.
What code do I need?
ModeCharacteristic_WriteRequestedAsync(modeCharacteristic, 5);
doesn't work.
I don't know how to use GattWriteRequestedEventArgs args or the event handler.
Write to Bluetooth LE Characteristic as a Server in WPF or UWP
You should process write operation in GattLocalCharacteristic ReadRequested, when the client send read request, you can get GattReadRequest in above event, and then call RespondWithValue to response data that written with data writer.
private async void ResultCharacteristic_ReadRequestedAsync(GattLocalCharacteristic sender, GattReadRequestedEventArgs args)
{
// BT_Code: Process a read request.
using (args.GetDeferral())
{
// Get the request information. This requires device access before an app can access the device's request.
GattReadRequest request = await args.GetRequestAsync();
if (request == null)
{
// No access allowed to the device. Application should indicate this to the user.
rootPage.NotifyUser("Access to device not allowed", NotifyType.ErrorMessage);
return;
}
var writer = new DataWriter();
writer.ByteOrder = ByteOrder.LittleEndian;
writer.WriteInt32(resultVal);
// Can get details about the request such as the size and offset, as well as monitor the state to see if it has been completed/cancelled externally.
// request.Offset
// request.Length
// request.State
// request.StateChanged += <Handler>
// Gatt code to handle the response
request.RespondWithValue(writer.DetachBuffer());
}
}
This is the code I'm now using. It works exactly like it should. First create a characteristic, then adding a subscribedClientsChanged eventhandler.
GattLocalCharacteristicResult result = await serviceProvider.Service.CreateCharacteristicAsync(Constants.ModusCharacteristicUuid, Constants.gattOperandParameters);
if (result.Error == BluetoothError.Success)
{
modeCharacteristic = result.Characteristic;
}
else
{
return false;
}
modeCharacteristic.SubscribedClientsChanged += ResultCharacteristic_SubscribedClientsChanged;
private void ResultCharacteristic_SubscribedClientsChanged(GattLocalCharacteristic sender, object args)
{
ModeNotify(5);
}
private async void ModeNotify(int computedValue)
{
var writer = new DataWriter();
writer.ByteOrder = ByteOrder.LittleEndian;
writer.WriteInt32(computedValue);
IReadOnlyList<GattClientNotificationResult> results = await modeCharacteristic.NotifyValueAsync(writer.DetachBuffer());
}

How to check if the device has biometrics

I am new to Xamarin forms and coding in general, I want to check if the device has biometrics as soon as the app is launched. I came across this video that shows how to do it using a button, I wanted to use it as soon as I open the app. can you help?
btnFPLogin.Clicked += FingerPrint;
private async void FingerPrint(object sender, EventArgs e)
{
var result = await CrossFingerprint.Current.IsAvailableAsync(true);
Plugin.Fingerprint.Abstractions.FingerprintAuthenticationResult auth;
if (result)
{
try
{
var res = await App.Current.MainPage.DisplayAlert("Success", "Your data are saved", "Ok", "Cancel");
auth = await CrossFingerprint.Current.AuthenticateAsync("Authenticate access");
if (auth.Authenticated)
{
await App.Current.MainPage.DisplayAlert("Results are here", "Valid fingerprint found", "Ok");
}
else
{
await App.Current.MainPage.DisplayAlert("Results are here", "Invalid fingerprint", "Ok");
}
}
catch
{
await App.Current.MainPage.DisplayAlert("permission to use FaceID", "We need permission to use FaceID", "Ok");
}
}
}
you've answered your own question. To check if a device supports biometric login, use the CrossFingerprint plugin
var result = await CrossFingerprint.Current.IsAvailableAsync(true);
if you want to check this on app launch, put it in the OnStart method of the App class

MVVM Light making an HTTP Get request using Webapi

I am a newbie when it comes to MVVM and Web related technologies. We are currently developing an MVVM client app using the latest MVVMLight framework in Visual Studios 2013. The application uses Microsoft's Webapi (latest version) to get data into our model via HTTP requests. Our code executes up to the point where the HTTP request is made, and we have confirmed that the server is getting the request, gathering up the requested data and returning it as JSON. However the client never sees the response, it just continues to wait for the response. Its almost as though we are seeing an issue that seems to do with threads. Where the request was made on one thread, but the response is being received on another. Here is our code (where the HTTP request is made):
public class DataService : IDataService
{
#region Fields
private HttpClient _client;
private LfActivityDataReturnObject _activityReturnObj;
private AdroServices _adroServices;
private bool _selectedProcssingOptionPosted = false;
private bool _activityDataSuccessfullyRetrieved = false;
private decimal _incomingLFEntryId;
#endregion
#region Constructor
public DataService()
{
try
{
//Get command line arguments
string[] arguments = Environment.GetCommandLineArgs();
for (int i = 1; i < arguments.Length; i++)
{
switch (i)
{
case 1:
{
if (!Decimal.TryParse(arguments[i], out _incomingLFEntryId))
{
_incomingLFEntryId = -1;
}
break;
}
}
}
if (_incomingLFEntryId <= 0)
{
throw new ArgumentException(String.Format("Invalid Activity Shortcut Entry ID: {0}", _incomingLFEntryId));
}
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region Methods
public void GetGeneralInformationModel(Action<GeneralInformationModel, Exception> callback)
{
Exception locException = null;
GeneralInformationModel locGeneralInformationModel = null;
if (_adroServices == null)
{
try
{
//Start the HTTP request
GetActivityDataAsync().Wait();
}
catch (Exception e)
{
locException = e;
}
// change? should be for http success but adro failure
if (_activityDataSuccessfullyRetrieved)
{
_adroServices = new AdroServices(_activityReturnObj);
locGeneralInformationModel = new GeneralInformationModel(_adroServices);
}
else
{
Exception e2 = new Exception("Error retrieving activity data in DataService");
locException = e2;
}
}
else
{
locGeneralInformationModel = new GeneralInformationModel(_adroServices);
}
var item = locGeneralInformationModel;
callback(item, locException);
}
//Get data from the repository via the service layer.
private async Task GetActivityDataAsync()
{
try
{
using (this._client = new HttpClient())
{
_client.BaseAddress = new Uri("http://localhost:52512//");
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Line below is where the app just runs getting no response
HttpResponseMessage caseDataResponse = await _client.GetAsync(string.Format("api/LfUrs/{0}", _incomingLFEntryId));
if (caseDataResponse.IsSuccessStatusCode)
{
_activityReturnObj = await caseDataResponse.Content.ReadAsAsync<LfActivityDataReturnObject>();
if (_activityReturnObj.ReturnCode == 0)
{
_activityDataSuccessfullyRetrieved = true;
}
else
{
_activityDataSuccessfullyRetrieved = false;
}
}
else
{
_activityDataSuccessfullyRetrieved = false;
}
}
}
catch (Exception ex)
{
_activityDataSuccessfullyRetrieved = false;
throw ex;
}
}
We have tried using Fiddler to get more information but Fiddler doesn't seem to be able to reveal any of the details. Also I should mention that we are simulating the server on the local host and as I stated above, we have confirmed the server gets the request and returns the data. My associates and I are starting to think this has something to do with the MVVM Light Framework and the IOC or possibly threading. When we use this same code in a MVVM solution that doesn't use the framework it works. Any help would be sincerely appreciated. Thanks...Mike
I have figured it out. Somehow, in my app.xaml, the Dispatcher.Helper had been moved to the event On_Startup rather than being contained in the class constructor. Additionally I had to move the HTTP stuff into the ADRO services class and make sure it was constructed in the App constructor in app.xaml right after Dispatcher.Helper. But thanks to everyone who participates here on StackOverFlow. This resource is an absolute life-saver. Thanks

Do not allow incoming call Lync Api or disabling sounds for incoming call

I have developed a windows application using Lync api. My client want to disable incoming calls to this application. So i have added some thing like this. I am able to cut the call but there are few rings before im able to do that
private void ClientInitialized(IAsyncResult result)
{
try
{
//registers for conversation related events
//these events will occur when new conversations are created (incoming/outgoing) and removed
client.ConversationManager.ConversationAdded += ConversationManager_ConversationAdded;
client.ConversationManager.ConversationRemoved += ConversationManager_ConversationRemoved;
}
catch (Exception ex)
{
MessageBox.Show("Problem in adding/removing conversation", "Bella IVIS", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void ConversationManager_ConversationAdded(object sender, ConversationManagerEventArgs e)
{
try
{
var _client = client;
if (e.Conversation.State == ConversationState.Active)
{
for (int intLoop = 0; intLoop < _client.ConversationManager.Conversations.Count; intLoop++)
{
_client.ConversationManager.Conversations[intLoop].End();
}
_client = null;
return;
}
}
}
I do not know if there is a way to capture conversation before Conversation_Added event. However, if the Lync status is not of any relevance to you then you change the Lync Status to "Do not disturb". This way you would never get any incoming request (unless the user Lync setting allow to do so)
var newInformation =new Dictionary<PublishableContactInformationType, object>();
newInformation.Add(PublishableContactInformationType.Availability, ContactAvailability.DoNotDisturb);
try
{
this.lyncClient.Self.BeginPublishContactInformation(newInformation,(result) => this.lyncClient.Self.EndPublishContactInformation(result) , null);
} catch {}

Connect to server with connect async

Is there any possible that I can ensure that the application does not fall if app can not connect to the server using await socket.ConnectAsync(server) I get this exc:
But the biggest problem is I get this exception only occasionally and randomly. Try and catch completely unresponsive and applications fall. So I need something if I cannot connect firts time dont go to exception but try it again.
My code:
public async Task _connect(string token, string idInstalation, string lang)
{
try
{
if (token != null)
{
socket.SetRequestHeader("Token", token);
socket.SetRequestHeader("Lang", lang);
socket.SetRequestHeader("idInstallation", idInstalation);
}
await socket.ConnectAsync(server);
System.Diagnostics.Debug.WriteLine("Connected");
writer = new DataWriter(socket.OutputStream);
messageNumber = 1;
}
catch (Exception)
{
var dialog = new MessageDialog("Cannot connect to UNIAPPS server", "Error").ShowAsync();
}
}

Categories