I have no idea why my code is not keeping players muted after they relog even though I added them to the config.
This is there the muted players get saved:
private static ArrayList <Player> mutedPlayers = new ArrayList<Player>();
This is the event that handles the muted player and that should check if the player is muted or not:
#EventHandler
public void handlePlayerChat(AsyncPlayerChatEvent e){
Player p = e.getPlayer();
if (mutedPlayers.contains(p)) {
p.sendMessage(ChatColor.DARK_RED + "You've been muted!");
e.setCancelled(true);
}
}
This is the command:
if(command.getName().equals("mute")) {
if (sender instanceof Player) {
Player p = (Player) sender;
if (p.hasPermission("shxr.mute")) {
if (args.length == 1) {
Player target = Bukkit.getPlayer(args[0]);
if (target != null) {
if (!mutedPlayers.contains(target)) {
mutedPlayers.add(target);
p.sendMessage(ChatColor.GREEN + "You have successfully muted " + target.getName() + ChatColor.GREEN + "!");
target.sendMessage(ChatColor.DARK_RED + "You are muted!");
getConfig().set("mutedPlayers.Players", mutedPlayers);
saveConfig();
} else {
mutedPlayers.remove(target);
p.sendMessage(ChatColor.GREEN + target.getName() + ChatColor.GREEN + " has been unmuted!");
target.sendMessage(ChatColor.DARK_RED + "You have been unmuted!");
saveConfig();
}
} else {
p.sendMessage(ChatColor.DARK_RED + "Cannot find the player.");
}
} else {
p.sendMessage(ChatColor.DARK_RED + "Proper usage of this command is: /mute <player>");
}
} else {
p.sendMessage(ChatColor.DARK_RED + "You do not have the permissions to mute players!");
}
}
}
Two issues:
You aren't saving this list to disk, so when the server restarts, you're going to lose it all.
You are storing references to the Player object, which gets recreated any time a user logs in or changes dimensions (Player is just an Entity class and is not a permanent reference). You need to store the user's UUID.
Related
I am trying to figure out why a response from the Volley library comes in twice (and it is not always the same response that is doubled).
This is the result, a pie chart:
As we can see the total income and the total spending comes in twice (and if I debug it, it is never 4 GET calls, it is always at least 6 GET calls, although only 4 methods are executed).
Here is my code where I am trying to execute 4 GET requests.
public void initialize() {
getOutputFromDatabase(StaticFields.INCOME);
getOutputFromDatabase(StaticFields.EXPENSE);
getOutputFromDatabase(StaticFields.SAVINGS);
getOutputFromDatabase(StaticFields.FOOD);
}
private void getOutputFromDatabase(String incomeOrExpenseOrSavingsOrFood) {
//RequestQueue initialized
mRequestQueue = Volley.newRequestQueue(this);
// REST URL
String url = null;
if(incomeOrExpenseOrSavingsOrFood.equals("income")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_INCOME;
} else if (incomeOrExpenseOrSavingsOrFood.equals("expense")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_EXPENSE;
} else if (incomeOrExpenseOrSavingsOrFood.equals("savings")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_SAVINGS;
} else if (incomeOrExpenseOrSavingsOrFood.equals("food")) {
url = StaticFields.PROTOCOL +
sharedPref_IP +
StaticFields.COLON +
sharedPref_Port +
StaticFields.REST_URL_GET_SUM_FOOD;
}
//String Request initialized
StringRequest mStringRequest = new StringRequest(Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj);
JSONObject locs = obj.getJSONObject("incomeexpense");
JSONArray recs = locs.getJSONArray("Total income");
String repl = recs.getString(0);
if(incomeOrExpenseOrSavingsOrFood.equals("income") && repl.equals("null")) {
totalIncome.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("income") && !repl.equals("null")){
totalIncome.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Total income",
Float.parseFloat(repl),
Color.parseColor("#99CC00")));
} else if(incomeOrExpenseOrSavingsOrFood.equals("expense") && repl.equals("null")) {
totalExpense.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("expense") && !repl.equals("null")) {
totalExpense.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Total spending",
Float.parseFloat(repl),
Color.parseColor("#FF4444")));
} else if(incomeOrExpenseOrSavingsOrFood.equals("savings") && repl.equals("null")) {
totalSavings.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("savings") && !repl.equals("null")) {
totalSavings.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Total savings",
Float.parseFloat(repl),
Color.parseColor("#33B5E5")));
} else if(incomeOrExpenseOrSavingsOrFood.equals("food") && repl.equals("null")) {
totalFood.setText("0");
} else if(incomeOrExpenseOrSavingsOrFood.equals("food") && !repl.equals("null")) {
totalFood.setText(repl);
pieChart.addPieSlice(
new PieModel(
"Food/day",
Float.parseFloat(repl),
Color.parseColor("#FFBB33")));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG,"Error :" + error.toString());
}
});
mStringRequest.setShouldCache(false);
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(5000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
mStringRequest.setRetryPolicy(retryPolicy);
mRequestQueue.add(mStringRequest);
// To animate the pie chart
pieChart.startAnimation();
}
Maybe someone know what I am doing wrong here?
I tried different things like
disabling the cache
setting a policy
but nothing worked so far.
I found my error.
The problem is that I am calling my methods where we can find the REST API calls in onResume again.
I had in my mind that onResume is called when someone comes back to his Activity, but I was wrong.
This is my right onResume now.
#Override
protected void onResume() {
super.onResume();
// pieChart.clearChart();
loadSharedPreferences(StaticFields.SP_PORT);
loadSharedPreferences(StaticFields.SP_INTERNET_ADDRESS);
loadSharedPreferences(StaticFields.SP_PERSON);
// getOutputFromDatabase(StaticFields.INCOME);
// getOutputFromDatabase(StaticFields.EXPENSE);
// getOutputFromDatabase(StaticFields.SAVINGS);
// getOutputFromDatabase(StaticFields.FOOD);
// To animate the pie chart
pieChart.startAnimation();
resetEditText();
}
I am using Unity IAP 4.1.4.
As you know there are 4 different test cards on purchase testing. My question is what should I do when payment is slow? If user quits the game before payment validated I can't approve the payment and purchase is pending. Is there any way to handle slow payments?
This is the script.
public class IAPManager : MonoBehaviour
{
private string coin250k = "//";
private string coin500k = "//";
public void OnPurchaseComplete(Product product)
{
var validator = new CrossPlatformValidator(GooglePlayTangle.Data(),AppleTangle.Data(), Application.identifier);
bool ValidPurchase = false;
try
{
// On Google Play, result has a single product ID.
// On Apple stores, receipts contain multiple products.
var result = validator.Validate(product.receipt);
// For informational purposes, we list the receipt(s)
Debug.Log("Receipt is valid. Contents:");
foreach (IPurchaseReceipt productReceipt in result)
{
Debug.Log(productReceipt.productID);
Debug.Log(productReceipt.purchaseDate);
Debug.Log(productReceipt.transactionID);
GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
if (null != google)
{
// This is Google's Order ID.
// Note that it is null when testing in the sandbox
// because Google's sandbox does not provide Order IDs.
ValidPurchase = true;
Debug.Log(" google transaction" + google.transactionID);
Debug.Log(" google transaction" + google.purchaseState);
Debug.Log(" google transaction" + google.purchaseToken);
}
AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
if (null != apple)
{
ValidPurchase = true;
Debug.Log(" apple transaction1" + apple.originalTransactionIdentifier);
Debug.Log(" apple transaction2" + apple.subscriptionExpirationDate);
Debug.Log(" apple transaction3" + apple.cancellationDate);
Debug.Log(" apple transaction4" + apple.quantity);
}
}
}
catch (IAPSecurityException)
{
Debug.Log("Invalid receipt, not unlocking content");
ValidPurchase = false;
}
//product.receipt;
if (ValidPurchase)
{
if (product.definition.id == coin250k)
{
//
}
else if (product.definition.id == coin500k)
{
//
}
}
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason reason)
{
Debug.Log(product.definition.id + " failed because: "+ reason);
}
}
I am tried to obtaining IP address using unity but I am unable to find it anywhere. If it is founded
then nothing seems to be worked.
https://docs.unity3d.com/ScriptReference/LocationService.Start.html
This is Unity official code which is not working at my end .It shows nothing .Similarly all types of codes not worked up.
Do you want to know IP address or Location? I don't know how can you get the user's IP address but there is a straightforward method for finding the user's location using GPS. If you want to do this, this youtube video will be useful for you ^^
Edit:
You can try this code that I found on this link. (Also check the linkie for more details)
public void GetUserLocation()
{
if( !Input.location.isEnabledByUser ) //FIRST IM CHACKING FOR PERMISSION IF "true" IT MEANS USER GAVED PERMISSION FOR USING LOCATION INFORMATION
{
statusTxt.text = "No Permission";
Permission.RequestUserPermission(Permission.FineLocation);
}
else
{
statusTxt.text = "Ok Permission";
StartCoroutine("GetLatLonUsingGPS");
}
}
IEnumerator GetLatLonUsingGPS()
{
Input.location.Start();
int maxWait = 5;
while( Input.location.status == LocationServiceStatus.Initializing && maxWait > 0 )
{
yield return new WaitForSeconds(1);
maxWait--;
}
if( maxWait < 1 )
{
statusTxt.text = "Failed To Iniyilize in 10 seconds";
yield break;
}
if( Input.location.status == LocationServiceStatus.Failed )
{
statusTxt.text = "Failed To Initialize";
yield break;
}
else
{
statusTxt.text ="waiting before getting lat and lon";
// yield return new WaitForSeconds(5);
// Access granted and location value could be retrieve
double longitude = Input.location.lastData.longitude;
double latitude = Input.location.lastData.latitude;
AddLocation(latitude, longitude);
statusTxt.text="" + Input.location.status + " lat:"+latitude+" long:"+longitude;
}
//Stop retrieving location
Input.location.Stop();
StopCoroutine("Start");
}
EDIT - 2:
For some reason, This code is not working and statusTxt is stuck on the "Failed To Iniyilize in 10 seconds" text. However, this problem is easy to solve! Just make it more straightforward! Remove all the if's in GetLatLonUsingGPS() method. My code was like that:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.UI;
public class GetLocations : MonoBehaviour
{
public Text statusTxt;
void Update()
{
GetUserLocation();
}
public void GetUserLocation()
{
if (!Input.location.isEnabledByUser) //FIRST IM CHACKING FOR PERMISSION IF "true" IT MEANS USER GAVED PERMISSION FOR USING LOCATION INFORMATION
{
statusTxt.text = "No Permission";
Permission.RequestUserPermission(Permission.FineLocation);
}
else
{
statusTxt.text = "Permission Granted";
StartCoroutine(GetLatLonUsingGPS());
}
}
IEnumerator GetLatLonUsingGPS()
{
Input.location.Start();
int maxWait = 5;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
maxWait--;
}
statusTxt.text = "waiting before getting lat and lon";
// Access granted and location value could be retrieve
double longitude = Input.location.lastData.longitude;
double latitude = Input.location.lastData.latitude;
//AddLocation(latitude, longitude);
statusTxt.text = "" + Input.location.status + " lat:" + latitude + " long:" + longitude;
//Stop retrieving location
Input.location.Stop();
StopCoroutine("Start");
}
}
There is only one problem in this code; don't call the GetUserLocation() method on the Update() method without any control bool or timer. Otherwise, StatusTxt will continuously change. For example, you can call it every 5 seconds.
I am using a non-consumable product to switch off ads for good, after purchasing.
When users buy pro everything works fine. Ads are switched off, also autorenewal in google store works fine after the user reinstalls the app.
My problem starts when the user wants a refund. After all, will be processed by Google and the customer will get his money. I don't know how where to subscribe to my function to turn off the pro version again on the users' app.
I am using IAPManager:
public class IAPManager : MonoBehaviour, IStoreListener
{
public List<Product> ProductList = new List<Product>();
public const string Pro = "pro";
private const string _androidPostFix = "_android";
[SerializeField] I18NText purchaseProBtnText;
public IAPManager Instance;
private void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
Init();
EventManager.PurchaseProduct += PurchaseProduct;
EventManager.GetProLocalizedPriceString += GetProLocalPriceString;
}
private void OnDestroy()
{
EventManager.PurchaseProduct -= PurchaseProduct;
EventManager.GetProLocalizedPriceString -= GetProLocalPriceString;
}
public List<Product> AllProducts { get { return m_Controller.products.all.ToList(); } }
private IStoreController m_Controller;
private ITransactionHistoryExtensions m_TransactionHistoryExtensions;
private IGooglePlayStoreExtensions m_GooglePlayStoreExtensions;
private bool m_IsGooglePlayStoreSelected;
private bool m_PurchaseInProgress;
#if RECEIPT_VALIDATION
private CrossPlatformValidator validator;
#endif
private string GetProLocalPriceString()
{
#if UNITY_ANDROID && !UNITY_EDITOR
foreach (Product product in ProductList)
{
if (product.metadata.localizedTitle == Pro)
{
return product.metadata.localizedPriceString;
}
}
return null;
#elif UNITY_EDITOR
foreach (Product product in ProductList)
{
if (product.metadata.localizedTitle == "Fake title for pro")
{
return product.metadata.localizedPriceString;
}
}
return null;
#endif
}
public void Init()
{
var module = StandardPurchasingModule.Instance();
module.useFakeStoreUIMode = FakeStoreUIMode.StandardUser;
var builder = ConfigurationBuilder.Instance(module);
// Set this to true to enable the Microsoft IAP simulator for local testing.
builder.Configure<IMicrosoftConfiguration>().useMockBillingSystem = false;
m_IsGooglePlayStoreSelected = Application.platform == RuntimePlatform.Android && module.appStore == AppStore.GooglePlay;
#if AGGRESSIVE_INTERRUPT_RECOVERY_GOOGLEPLAY
// For GooglePlay, if we have access to a backend server to deduplicate purchases, query purchase history
// when attempting to recover from a network-interruption encountered during purchasing. Strongly recommend
// deduplicating transactions across app reinstallations because this relies upon the on-device, deletable
// TransactionLog database.
builder.Configure<IGooglePlayConfiguration>().aggressivelyRecoverLostPurchases = true;
// Use purchaseToken instead of orderId for all transactions to avoid non-unique transactionIDs for a
// single purchase; two ProcessPurchase calls for one purchase, differing only by which field of the receipt
// is used for the Product.transactionID. Automatically true if aggressivelyRecoverLostPurchases is enabled
// and this API is not called at all.
builder.Configure<IGooglePlayConfiguration>().UsePurchaseTokenForTransactionId(true);
#endif
//builder.AddProduct(Pro, ProductType.NonConsumable);
builder.AddProduct(Pro, ProductType.NonConsumable, new IDs
{
{Pro, GooglePlay.Name},
//{Pro+_iosPostFix, AppleAppStore.Name}
}
);
#if INTERCEPT_PROMOTIONAL_PURCHASES
// On iOS and tvOS we can intercept promotional purchases that come directly from the App Store.
// On other platforms this will have no effect; OnPromotionalPurchase will never be called.
builder.Configure<IAppleConfiguration>().SetApplePromotionalPurchaseInterceptorCallback(OnPromotionalPurchase);
Debug.Log("Setting Apple promotional purchase interceptor callback");
#endif
#if RECEIPT_VALIDATION
string appIdentifier;
#if UNITY_5_6_OR_NEWER
appIdentifier = Application.identifier;
#else
appIdentifier = Application.bundleIdentifier;
#endif
try
{
validator = new CrossPlatformValidator(GooglePlayTangle.Data(), AppleTangle.Data(), appIdentifier);
}
catch (NotImplementedException exception)
{
Debug.Log("Cross Platform Validator Not Implemented: " + exception);
}
#endif
// Now we're ready to initialize Unity IAP.
UnityPurchasing.Initialize(this, builder);
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
m_Controller = controller;
m_TransactionHistoryExtensions = extensions.GetExtension<ITransactionHistoryExtensions>();
m_GooglePlayStoreExtensions = extensions.GetExtension<IGooglePlayStoreExtensions>();
#if SUBSCRIPTION_MANAGER
Dictionary<string, string> introductory_info_dict = m_AppleExtensions.GetIntroductoryPriceDictionary();
#endif
// Sample code for expose product sku details for apple store
//Dictionary<string, string> product_details = m_AppleExtensions.GetProductDetails();
Debug.Log("Available items:");
foreach (var item in controller.products.all)
{
if (item.availableToPurchase)
{
Debug.Log(string.Join(" - ",
new[]
{
item.metadata.localizedTitle,
item.metadata.localizedDescription,
item.metadata.isoCurrencyCode,
item.metadata.localizedPrice.ToString(),
item.metadata.localizedPriceString,
item.transactionID,
item.receipt
}));
ProductList.Add(item);
#if INTERCEPT_PROMOTIONAL_PURCHASES
// Set all these products to be visible in the user's App Store according to Apple's Promotional IAP feature
// https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/PromotingIn-AppPurchases/PromotingIn-AppPurchases.html
m_AppleExtensions.SetStorePromotionVisibility(item, AppleStorePromotionVisibility.Show);
#endif
#if SUBSCRIPTION_MANAGER
// this is the usage of SubscriptionManager class
if (item.receipt != null) {
if (item.definition.type == ProductType.Subscription) {
if (checkIfProductIsAvailableForSubscriptionManager(item.receipt)) {
string intro_json = (introductory_info_dict == null || !introductory_info_dict.ContainsKey(item.definition.storeSpecificId)) ? null : introductory_info_dict[item.definition.storeSpecificId];
SubscriptionManager p = new SubscriptionManager(item, intro_json);
SubscriptionInfo info = p.getSubscriptionInfo();
Debug.Log("product id is: " + info.getProductId());
Debug.Log("purchase date is: " + info.getPurchaseDate());
Debug.Log("subscription next billing date is: " + info.getExpireDate());
Debug.Log("is subscribed? " + info.isSubscribed().ToString());
Debug.Log("is expired? " + info.isExpired().ToString());
Debug.Log("is cancelled? " + info.isCancelled());
Debug.Log("product is in free trial peroid? " + info.isFreeTrial());
Debug.Log("product is auto renewing? " + info.isAutoRenewing());
Debug.Log("subscription remaining valid time until next billing date is: " + info.getRemainingTime());
Debug.Log("is this product in introductory price period? " + info.isIntroductoryPricePeriod());
Debug.Log("the product introductory localized price is: " + info.getIntroductoryPrice());
Debug.Log("the product introductory price period is: " + info.getIntroductoryPricePeriod());
Debug.Log("the number of product introductory price period cycles is: " + info.getIntroductoryPricePeriodCycles());
} else {
Debug.Log("This product is not available for SubscriptionManager class, only products that are purchase by 1.19+ SDK can use this class.");
}
} else {
Debug.Log("the product is not a subscription product");
}
} else {
Debug.Log("the product should have a valid receipt");
}
#endif
}
}
}
public void Restore()
{
m_GooglePlayStoreExtensions.RestoreTransactions(OnTransactionsRestored);
Debug.Log("Restore method");
}
private void OnTransactionsRestored(bool success)
{
Debug.Log("Transactions restored." + success);
}
public void OnPurchaseFailed(Product item, PurchaseFailureReason r)
{
Debug.Log("Purchase failed: " + item.definition.id);
Debug.Log(r);
// Detailed debugging information
Debug.Log("Store specific error code: " + m_TransactionHistoryExtensions.GetLastStoreSpecificPurchaseErrorCode());
if (m_TransactionHistoryExtensions.GetLastPurchaseFailureDescription() != null)
{
Debug.Log("Purchase failure description message: " +
m_TransactionHistoryExtensions.GetLastPurchaseFailureDescription().message);
}
m_PurchaseInProgress = false;
}
public void OnInitializeFailed(InitializationFailureReason error)
{
Debug.Log("Billing failed to initialize!");
switch (error)
{
case InitializationFailureReason.AppNotKnown:
Debug.LogError("Is your App correctly uploaded on the relevant publisher console?");
break;
case InitializationFailureReason.PurchasingUnavailable:
// Ask the user if billing is disabled in device settings.
Debug.Log("Billing disabled!");
break;
case InitializationFailureReason.NoProductsAvailable:
// Developer configuration error; check product metadata.
Debug.Log("No products available for purchase!");
break;
}
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e)
{
Debug.Log("Purchase OK: " + e.purchasedProduct.definition.id);
Debug.Log("Receipt: " + e.purchasedProduct.receipt);
m_PurchaseInProgress = false;
#if RECEIPT_VALIDATION // Local validation is available for GooglePlay, and Apple stores
if (m_IsGooglePlayStoreSelected ||
Application.platform == RuntimePlatform.IPhonePlayer ||
Application.platform == RuntimePlatform.OSXPlayer ||
Application.platform == RuntimePlatform.tvOS) {
try {
var result = validator.Validate(e.purchasedProduct.receipt);
Debug.Log("Receipt is valid. Contents:");
foreach (IPurchaseReceipt productReceipt in result) {
Debug.Log(productReceipt.productID);
Debug.Log(productReceipt.purchaseDate);
Debug.Log(productReceipt.transactionID);
GooglePlayReceipt google = productReceipt as GooglePlayReceipt;
if (null != google) {
Debug.Log(google.purchaseState);
Debug.Log(google.purchaseToken);
}
AppleInAppPurchaseReceipt apple = productReceipt as AppleInAppPurchaseReceipt;
if (null != apple) {
Debug.Log(apple.originalTransactionIdentifier);
Debug.Log(apple.subscriptionExpirationDate);
Debug.Log(apple.cancellationDate);
Debug.Log(apple.quantity);
}
// For improved security, consider comparing the signed
// IPurchaseReceipt.productId, IPurchaseReceipt.transactionID, and other data
// embedded in the signed receipt objects to the data which the game is using
// to make this purchase.
}
}
catch (IAPSecurityException ex)
{
Debug.Log("Invalid receipt, not unlocking content. " + ex);
return PurchaseProcessingResult.Complete;
}
catch (NotImplementedException exception)
{
Debug.Log("Cross Platform Validator Not Implemented: " + exception);
}
}
#endif
// Unlock content from purchases here.
if (e.purchasedProduct.definition.id == Pro)
{
//PlayerPrefs.SetInt("pro", 1);
Debug.Log("PURCHASED PRODUCT!");
//AdsManager.Instance.ProActive = true;
AdsManager.Instance.HideAdsPro();
//EventBroker.CallOnProBought();
}
#if USE_PAYOUTS
if (e.purchasedProduct.definition.payouts != null) {
Debug.Log("Purchase complete, paying out based on defined payouts");
foreach (var payout in e.purchasedProduct.definition.payouts) {
Debug.Log(string.Format("Granting {0} {1} {2} {3}", payout.quantity, payout.typeString, payout.subtype, payout.data));
}
}
#endif
#if DELAY_CONFIRMATION
StartCoroutine(ConfirmPendingPurchaseAfterDelay(e.purchasedProduct));
return PurchaseProcessingResult.Pending;
#else
return PurchaseProcessingResult.Complete;
#endif
}
/// <summary>
/// Call this method to start purchase product.
/// </summary>
/// <param name="productID">Product ID from products on Google Dev Dashboard</param>
public void PurchaseProduct(string productID)
{
Debug.Log("PurchaseProduct");
if (m_PurchaseInProgress == true)
{
Debug.Log("Please wait, purchase in progress");
return;
}
if (m_Controller == null)
{
Debug.LogError("Purchasing is not initialized");
return;
}
if (m_Controller.products.WithID(productID) == null)
{
Debug.LogError("No product has id " + productID);
return;
}
m_PurchaseInProgress = true;
m_Controller.InitiatePurchase(m_Controller.products.WithID(productID), "developerPayload");
}
}
I found a solution myself.
I checked product.hasRecipt to get info if the product is bought.
So the receipt disappears after a successful revoke process in the google app store.
And every time the app is restarted this bool is sent to the app during IAP initialization.
I'm currently developping a bungeecord plugin for my server but It's two days that I'm searching for a problem and any forum have the answer.
My problem:
I don't want to create a spigot/bukkit plugin that I have to place in all my server.
My problem is that I want that a player that have a permission like VelocityPerm.Legend when he write something on the chat the format is :
PlayerName [LEGEND] What the player write
This is my code :
#EventHandler
public void onChat(ChatEvent e) {
String line = e.getMessage();
if(!line.startsWith("/")){
ProxiedPlayer p = (ProxiedPlayer) e.getSender();
String message = e.getMessage();
if(p.hasPermission("VelocityPerm.Founder")) {
e.setMessage(ChatColor.DARK_RED + "[FOUNDER]: " + ChatColor.WHITE + message);
}
}
}
How to do it ?.
You have to create a bungee event on your bungee plugin like that :
#EventHandler
public void onChat(ChatEvent e) {
ProxiedPlayer p = (ProxiedPlayer) e.getSender();
if(e.isCommand()) { // check if it's a command, to cancel it or not
// here you can manage when it's a command.
// but when we are here, it's NOT a chat message.
} else { // it's a chat message
if(p.hasPermission("VelocityPerm.Legend")) { // check if has permission
e.setMessage("[Legend] " + p.getName() + ": " + ChatColor.WHITE + e.getMessage()); // change message
}
}
}
Don't forget to register your event :
#Override
public void onEnable() {
getProxy().getPluginManager().registerListener(this, new MyChatEvent());
}