using System; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; class Program { public static readonly int POST_CRAWLER_INTERVAL = 1; public static readonly int REQUEST_GOD_INTERVAL = 10 * 1000; // 10 secs public static readonly int TOKEN_UPDATER_INTERVAL = 10 * 1000; // 10 secs public static readonly int CAPTAIN_COLD_INTERVAL = 6 * 1000 * 60 * 60; //6 Hours private static readonly string bearerToken = "AAAAAAAAAAAAAAAAAAAAANw1uQEAAAAAe7iEwpMcF%2FjNUZ4WLxEHpax3Ywg%3D0PV1pvJB23a47hWAIwB09olQesVhsz9fPKLg8edP2cwC5D6YHW"; private static readonly string searchUrl = "https://api.twitter.com/2/tweets/search/recent"; static async Task Main(string[] args) { StartPostCrawler(); StartRequestGod(); StartTokenCrawler(); StartCptCold(); while (true) { await Task.Delay(1000); } } static async void StartCptCold(){ while(true){ List frozenWeekly = new List(); List frozenMonthly = new List(); using (HttpClient client = new HttpClient()) { string requestUrl = "https://api.callfi.io/get_all_callouts_history.php"; HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); JArray callouts = JArray.Parse(jsonResponse); for(int i=0; i < callouts.Count; i++){ if(callouts[i]["period"].ToString() == "week"){ frozenWeekly.Add(callouts[i]["callout_id"].ToString()); }else{ frozenMonthly.Add(callouts[i]["callout_id"].ToString()); } } } } using (HttpClient client = new HttpClient()) { string requestUrl = "https://api.callfi.io/get_all_callouts.php"; HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); JArray callouts = JArray.Parse(jsonResponse); for(int i=0; i < callouts.Count; i++){ DateTime addedDate = DateTime.Parse(callouts[i]["added_date"].ToString()); if(!frozenWeekly.Contains(callouts[i]["id"].ToString())){ DateTime nextWeek = HelperMethods.GetNextMonday(addedDate); Console.WriteLine($"next monday from {addedDate} is {nextWeek}"); if(DateTime.Now > nextWeek){ await FreezeCallout(callouts[i]["id"].ToString(), "week"); } } if(!frozenWeekly.Contains(callouts[i]["id"].ToString())){ DateTime nextMonth = HelperMethods.GetNextFirstDay(addedDate); Console.WriteLine($"next month from {addedDate} is {nextMonth}"); if(DateTime.Now > nextMonth){ await FreezeCallout(callouts[i]["id"].ToString(), "month"); } } } } } await Task.Delay(CAPTAIN_COLD_INTERVAL); } } static async Task FreezeCallout(string id, string period = "week"){ using (HttpClient client = new HttpClient()) { string requestUrl = $"https://api.callfi.io/add_callout_history.php?id={id}&period={period}"; HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); } } } static async void StartRequestGod() { string requestUrl = $"https://api.callfi.io/get_requests.php"; while (true) { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); JArray requests = JArray.Parse(jsonResponse); for (int i = 0; i < requests.Count; i++) { string reqType = (requests[i]["request_type"] ?? "").ToString(); string reqId = requests[i]["id"].ToString(); if (reqType == "twitter_id") { string userTag = requests[i]["request_data"].ToString(); List userdata = await GetTwitterId(userTag); string userId = userdata[0]; string userImgUrl = userdata[1]; if (userId.Length > 0) { //Update twitter map await AddTwitterTag(userTag, userId,userImgUrl, reqId); } } } } else { Console.WriteLine($"Request failed: {response.StatusCode} - {response.ReasonPhrase}"); } } await Task.Delay(REQUEST_GOD_INTERVAL); } } static async Task> GetTwitterId(string userTag) { if(userTag.Length < 2){return new List();} string requestUrl = $"https://api.twitter.com/2/users/by/username/{userTag.Replace("@", "")}?user.fields=profile_image_url"; List data = new List(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); Console.WriteLine(requestUrl); HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); JObject userObj = JObject.Parse(jsonResponse); data.Add((userObj["data"]["id"] ?? "").ToString()); data.Add((userObj["data"]["profile_image_url"] ?? "").ToString()); } else { Console.WriteLine($"Request failed id: {response.StatusCode} - {response.ReasonPhrase} : {requestUrl}"); } } return data; } static async Task AddTwitterTag(string userTag, string userId,string userImgUrl, string reqId) { await CompleteRequest(reqId, userId); string requestUrl = $"https://api.callfi.io/add_twitter_tag.php?userTag={userTag}&userId={userId}&userImgUrl={userImgUrl}"; using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); if (jsonResponse == "0") { //Done } } else { Console.WriteLine($"Request failed twittTag: {response.StatusCode} - {response.ReasonPhrase}"); } } } static async Task CompleteRequest(string reqId, string remark) { string requestUrl = $"https://api.callfi.io/complete_request.php?id={reqId}&remarks={remark}"; Console.WriteLine(requestUrl); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); if (jsonResponse == "0") { //Done } } else { Console.WriteLine($"Request failed complete request: {response.StatusCode} - {response.ReasonPhrase}"); } } } //sk-proj-okUjDHtCh22PaAuFZgraT3BlbkFJRinfIM5NwbU0zffUVRFq static bool kickstarted = false; static async void StartPostCrawler() { string searchString = "CallFi"; string query = Uri.EscapeDataString(searchString); while (true) { DateTime now = DateTime.UtcNow; DateTime startTime = now.AddMinutes(-POST_CRAWLER_INTERVAL * (kickstarted ? 1: 15)); kickstarted =true; string startTimeStr = startTime.ToString("yyyy-MM-ddTHH:mm:ssZ"); string endTimeStr = now.ToString("yyyy-MM-ddTHH:mm:ssZ"); string requestUrl = $"{searchUrl}?query={query}&max_results=50&start_time={startTimeStr}&tweet.fields=author_id,created_at"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); HttpResponseMessage response = await client.GetAsync(requestUrl); Console.WriteLine(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); JObject tweets = JObject.Parse(jsonResponse); File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + $"/results_{DateTime.Now.Year}_{DateTime.Now.Month}_{DateTime.Now.Day}-{DateTime.Now.Hour}-{DateTime.Now.Minute}.txt", tweets.ToString()); Console.WriteLine(tweets.ToString()); try { JArray tweetsData = JArray.Parse(tweets["data"].ToString()); for (int i = 0; i < tweetsData.Count; i++) { string tweetId = tweetsData[i]["id"].ToString(); string tweetText = tweetsData[i]["text"].ToString(); string tweetAuthor = tweetsData[i]["author_id"].ToString(); string created_at = tweetsData[i]["created_at"].ToString(); string chatGPTResponse = await CalloutAskChatGPT(tweetText); JObject chatGPTJson = JObject.Parse(chatGPTResponse); string code = chatGPTJson["tokenId"].ToString(); string name = chatGPTJson["tokenName"].ToString(); string ca = chatGPTJson["ca"].ToString(); if(code == "null"){ string partChatGPTResponse = await ParticipationAskChatGPT(tweetText); if(partChatGPTResponse.ToLower().Contains("yes")){ await Participation(tweetAuthor); }else{ Console.WriteLine($"Ignoring tweet {tweetText}"); } continue; //false alarm } // if (data[0] == "yes") // { // code = data[1]; // name = (data.Length > 2) ? data[2] : "unknown"; // }else{ // //Check if participation tweet // string partChatGPTResponse = await ParticipationAskChatGPT(tweetText); // if(partChatGPTResponse.ToLower().Contains("yes")){ // await Participation(tweetAuthor); // }else{ // Console.WriteLine($"Ignoring tweet {tweetText}"); // } // continue; // } if(ca.Length < 8){ ca =await GetTokenCa(code); } Console.WriteLine("New tweet with ca "+ ca); if(ca.Length > 6){ await AddToken(code, name, ca); } await AddTweet(tweetId, created_at, tweetText, tweetAuthor, code, name,ca); } } catch { Console.WriteLine("None"); } } else { Console.WriteLine($"Request failed Twitter fetch: {response.StatusCode} - {response.ReasonPhrase}"); } } await Task.Delay(POST_CRAWLER_INTERVAL * 60 * 1000); } } static async Task AddToken(string id, string name, string ca){ string _ca = ca; if(_ca.Length < 8){ //not a valid ca _ca = await GetTokenCa(id); }else{ //validate user entered ca } string requestUrl = $"https://api.callfi.io/add_token.php?ca={_ca}&name={name}&code={id}"; Console.WriteLine(requestUrl); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); if (jsonResponse == "0") { Console.WriteLine($"New token added, {id}-{name} : {_ca}"); //Done } } else { Console.WriteLine($"Request failed complete request: {response.StatusCode} - {response.ReasonPhrase}"); } } } static async Task GetTokenCa(string code){ string requestUrl = $"https://api.callfi.io/get_token_ca.php?code={code}"; Console.WriteLine(requestUrl); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); return jsonResponse; } else { Console.WriteLine($"Request failed complete request: {response.StatusCode} - {response.ReasonPhrase}"); } } return "null"; } static async Task GetTokenId(string code, string name, string ca){ string requestUrl = $"https://api.callfi.io/get_token_id.php?ca={ca}&name={name}&code={code}"; Console.WriteLine(requestUrl); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); return int.Parse(jsonResponse); } else { Console.WriteLine($"Request failed complete request: {response.StatusCode} - {response.ReasonPhrase}"); } } return -1; } static async Task AddTweet(string id, string createdAt, string text, string author, string tokenCode, string tokenName,string ca) { string requestUrl = $"https://api.callfi.io/add_tweet.php?tweet_id={id}&created_at={createdAt}&author_id={author}&text={Uri.EscapeDataString(text)}&token_code={Uri.EscapeDataString(tokenCode)}&token_name={Uri.EscapeDataString(tokenName)}&ca={ca}"; Console.WriteLine(requestUrl); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); if (jsonResponse == "0") { //Done } } else { Console.WriteLine($"Request failed complete request: {response.StatusCode} - {response.ReasonPhrase}"); } } } static async Task Participation(string author) { string requestUrl = $"https://api.callfi.io/participate.php?author_id={author}"; Console.WriteLine(requestUrl); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); if (jsonResponse == "0") { //Done } } else { Console.WriteLine($"Request failed complete request: {response.StatusCode} - {response.ReasonPhrase}"); } } } static async void UpdateLeaderboard() { await UpdateTokens(); string requestUrl = "https://api.callfi.io/get_tweets.php"; List Tokens = new List(); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { JArray jsonArr = JArray.Parse(await response.Content.ReadAsStringAsync()); Dictionary TwitterHandles = new Dictionary(); List callouts = new List(); foreach(JObject tweet in jsonArr){ string tokenId = tweet["tokenId"].ToString().Replace(" ",""); if(!Tokens.Contains(tokenId)){ Tokens.Add(tokenId); } string userId = tweet["author"].ToString().Replace(" ", ""); if(!TwitterHandles.ContainsKey(userId)){ HttpResponseMessage usernameResponse = await client.GetAsync("https://api.callfi.io/get_twitter_username.php?id="+userId); string usernameTxt = await usernameResponse.Content.ReadAsStringAsync(); TwitterHandles.Add(userId, usernameTxt); } } Dictionary TokenPrices = new Dictionary(); foreach(string token in Tokens){ try{ HttpResponseMessage priceResponse = await client.GetAsync("https://api.callfi.io/get_token_price_by_ca.php?ca="+token); string priceResponseTxt = await priceResponse.Content.ReadAsStringAsync(); decimal price = decimal.Parse(priceResponseTxt); TokenPrices.Add(token,price); }catch(Exception e){ Console.WriteLine("Failed to get price of " + token); } } Dictionary Leaderboard = new Dictionary(); foreach(JObject tweet in jsonArr){ string tokenId = tweet["tokenCode"].ToString().Replace(" ",""); string tokenCa = tweet["tokenId"].ToString().Replace(" ",""); decimal priceAtCreation = decimal.Parse(tweet["price_at_creation"].ToString()); decimal priceDiff = TokenPrices[tokenCa] - priceAtCreation; decimal priceDiffPerc = priceDiff / priceAtCreation; decimal pointsAdded= priceDiffPerc; string userTag = TwitterHandles[tweet["author"].ToString()]; if(!userTag.Contains("@")){continue;} if(Leaderboard.ContainsKey(userTag)){ Leaderboard[userTag] += pointsAdded; }else{ Leaderboard.Add(userTag, pointsAdded); } bool alreadyCalled = false; foreach(CalloutData callout in callouts){ if(callout.username == userTag && callout.token == tokenId){ alreadyCalled=true; } } if(!alreadyCalled){ callouts.Add(new CalloutData(){username=userTag, token=tokenId, price_at_creation=priceAtCreation.ToString(),price_now=TokenPrices[tokenCa].ToString(),gains=pointsAdded.ToString(), addedDate=tweet["created_at"].ToString(), ca=tokenCa}); } } List approvedUsers = await GetApprovedUsers(); foreach(string approvedUser in approvedUsers){ if(!Leaderboard.ContainsKey(approvedUser)){ Leaderboard.Add(approvedUser,0); } } Console.WriteLine(JsonConvert.SerializeObject(Leaderboard)); foreach(KeyValuePair leaderboardItem in Leaderboard){ string setLeaderboardItemUrl = $"https://api.callfi.io/set_leaderboard_item.php?username={leaderboardItem.Key}&points={leaderboardItem.Value}"; HttpResponseMessage priceResponse = await client.GetAsync(setLeaderboardItemUrl); // Console.WriteLine(setLeaderboardItemUrl); string priceResponseTxt = await priceResponse.Content.ReadAsStringAsync(); } foreach(CalloutData callout in callouts){ string setCalloutItemUrl = $"https://api.callfi.io/set_callout_item.php?username={callout.username}&token={callout.token}&price_at_creation={callout.price_at_creation}&price_now={callout.price_now}&gains={callout.gains}&ca={callout.ca}&added_date={callout.addedDate}"; HttpResponseMessage priceResponse = await client.GetAsync(setCalloutItemUrl); Console.WriteLine(setCalloutItemUrl); } } else { Console.WriteLine($"Request failed: {response.StatusCode} - {response.ReasonPhrase}"); } } } static async Task> GetApprovedUsers(){ string requestUrl = "https://api.callfi.io/get_approved_users.php"; List output = new List(); using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { JArray usersJ = JArray.Parse(await response.Content.ReadAsStringAsync()); for(int i=0;i < usersJ.Count; i++){ output.Add(usersJ[i].ToString()); } } else { Console.WriteLine($"Request failed: {response.StatusCode} - {response.ReasonPhrase}"); } } return output; } static async Task CalloutAskChatGPT(string text) { string context = @"I need you to analyze this tweet I'm gonna send you. I'm looking for a callout on a crypto token to go high. Typically, users say this like 'Hit the moon, WAGMI, lambo' and many other slangs. I need you to extract info about the crypto token they mentioned in this tweet. You must respond in JSON. Here is an example tweet. $COC #Choir of Cats is Going to the moon! CA: 9g6NpisYK3aaiNXnjTLjh67NhQfEzv7qVk24fCijXxFR #CallFi #CallingIt Your response must be like: Just the JSON output. I'm using this for a tool. No other texts. Just the JSON so I can parse it. { ""tokenId"": ""COC"", ""tokenName"": ""Choir of Cats"", ""ca"": ""9g6NpisYK3aaiNXnjTLjh67NhQfEzv7qVk24fCijXxFR"" }"; HttpClient client = new HttpClient(); var url = "https://api.openai.com/v1/chat/completions"; var apiKey = "sk-proj-AUdPozaNLwzgZiFDty8HT3BlbkFJfJDONAwRJwfFmZ56nAZo"; var requestData = new { model = "gpt-3.5-turbo", messages = new[] { new { role = "user", content = context }, new {role = "user", content = text} }, temperature = 0.7 }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(requestData); var requestMessage = new HttpRequestMessage(HttpMethod.Post, url); requestMessage.Headers.Add("Authorization", $"Bearer {apiKey}"); requestMessage.Content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.SendAsync(requestMessage); var responseString = await response.Content.ReadAsStringAsync(); JObject resposneJson = JObject.Parse(responseString); string resContent = resposneJson["choices"][0]["message"]["content"].ToString(); Console.WriteLine(resContent); return resContent; } static async Task ParticipationAskChatGPT(string text) { string context = @"Check if next message im gonna send you, is a participation post for my platform which is called CallFi, a platform for calling out upcoming tokens, Simply respond 'yes' or 'no' if it is a participation tweet with a mention to the web link callfi.io"; HttpClient client = new HttpClient(); var url = "https://api.openai.com/v1/chat/completions"; var apiKey = "sk-proj-AUdPozaNLwzgZiFDty8HT3BlbkFJfJDONAwRJwfFmZ56nAZo"; var requestData = new { model = "gpt-3.5-turbo", messages = new[] { new { role = "user", content = context }, new {role = "user", content = text} }, temperature = 0.7 }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(requestData); var requestMessage = new HttpRequestMessage(HttpMethod.Post, url); requestMessage.Headers.Add("Authorization", $"Bearer {apiKey}"); requestMessage.Content = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.SendAsync(requestMessage); var responseString = await response.Content.ReadAsStringAsync(); JObject resposneJson = JObject.Parse(responseString); string resContent = resposneJson["choices"][0]["message"]["content"].ToString(); Console.WriteLine(resContent); return resContent; } static async void StartTokenCrawler() { while (true) { await UpdateTokens(); UpdateLeaderboard(); await Task.Delay(TOKEN_UPDATER_INTERVAL); } } static async Task UpdateTokens(){ string requestUrl = "https://api.callfi.io/get_all_tokens.php"; using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { JArray array = JArray.Parse(await response.Content.ReadAsStringAsync()); Console.WriteLine("Updating " + array.Count + " tokens"); for(int i=0; i < array.Count; i++){ string ca = array[i]["ca"].ToString(); string newPrice = await GetTokenPriceRealtime(ca); await SetNewTokenPrice(ca, newPrice); if(array[i]["icon_url"] == null){ await UpdateTokenImage(ca); }else{ if(!array[i]["icon_url"].ToString().Contains("http")){ await UpdateTokenImage(ca); } } } } else { Console.WriteLine($"Request failed:{requestUrl} => {response.StatusCode} - {response.ReasonPhrase}"); } } } static async Task GetTokenPriceRealtime(string ca){ string requestUrl = $"http://api.callfi.io/get_token_price_dex.php?ca={ca}"; using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { string result= await response.Content.ReadAsStringAsync(); return result; } else { Console.WriteLine($"Request failed: {response.StatusCode} - {response.ReasonPhrase}"); } } return "0"; } static async Task SetNewTokenPrice(string ca, string newPrice){ string requestUrl = $"https://api.callfi.io/set_token_price.php?ca={ca}&price={newPrice}"; using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { } else { Console.WriteLine($"Request failed:{requestUrl} => {response.StatusCode} - {response.ReasonPhrase}"); } } } static async Task UpdateTokenImage(string ca){ string requestUrl = $"https://api.callfi.io/update_token_image.php?ca={ca}"; using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { } else { Console.WriteLine($"Request failed:{requestUrl} => {response.StatusCode} - {response.ReasonPhrase}"); } } } static async Task UpdateTokensOld() { string requestUrl = "https://api.callfi.io/get_tokens.php"; using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(requestUrl); if (response.IsSuccessStatusCode) { } else { Console.WriteLine($"Request failed: {response.StatusCode} - {response.ReasonPhrase}"); } } } }