- 
                Notifications
    
You must be signed in to change notification settings  - Fork 7
 
Feature mail scheduler #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            Loulou5702
  wants to merge
  5
  commits into
  marmelab:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
theosli:feature/periodicity
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            5 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      7910f17
              
                Example Scheduler without mail sending
              
              
                Loulou5702 229c7b2
              
                fix : rename + fixing bug
              
              
                Loulou5702 044e960
              
                fix : added a flag to disable the log
              
              
                Loulou5702 e72bb62
              
                [feat] Added cron instead of setInterval for periodicity
              
              
                Aurelien-Gindre 5f0fc70
              
                feature : extract periodicity preferences from txt and modify the DB
              
              
                Loulou5702 File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| import { exec } from "child_process"; | ||
| import { createClient } from "@supabase/supabase-js"; | ||
| import dotenv from "dotenv"; | ||
| import cron from "node-cron"; | ||
| 
     | 
||
| dotenv.config({ path: "./../.env" }); | ||
| 
     | 
||
| const supabaseUrl = process.env.SUPABASE_URL; | ||
| const supabaseAnonKey = process.env.SUPABASE_ANON_KEY; | ||
| if (!supabaseUrl || !supabaseAnonKey) { | ||
| throw new Error("❌ Missing Supabase credentials."); | ||
| } | ||
| 
     | 
||
| const supabase = createClient(supabaseUrl, supabaseAnonKey); | ||
| const loggingActivated = true; // Set to false to disable logs | ||
| 
     | 
||
| // Main | ||
| console.log("🟢 Newsletter Scheduler started... Press CTRL + C to stop."); | ||
| cron.schedule('* * * * *', checkAndSendNewsletters); | ||
| 
     | 
||
| // Functions | ||
| async function getPendingNewsletters() { | ||
| const currentISO = new Date().toISOString(); | ||
| const { data, error } = await supabase | ||
| .from("subscribers") | ||
| .select("id, user_email, next_newsletter, periodicity") | ||
| .lte("next_newsletter", currentISO); | ||
| 
     | 
||
| if (error) { | ||
| console.error("❌ Error fetching pending newsletters:", error); | ||
| return []; | ||
| } | ||
| return data; | ||
| } | ||
| 
     | 
||
| async function updateNextNewsletter(userId: number, periodicity: number) { | ||
| const newNewsletterTimestampSeconds = Math.floor(Date.now() / 1000) + periodicity; | ||
| const newNewsletterISO = new Date(newNewsletterTimestampSeconds * 1000).toISOString(); | ||
| 
     | 
||
| const { error } = await supabase | ||
| .from("subscribers") | ||
| .update({ next_newsletter: newNewsletterISO }) | ||
| .eq("id", userId); | ||
| 
     | 
||
| if (error) { | ||
| console.error(`❌ Error updating next newsletter for user ID ${userId}:`, error); | ||
| } else if (loggingActivated) { | ||
| console.log(`📅 Next newsletter for user ID ${userId} scheduled at ${newNewsletterISO}`); | ||
| } | ||
| } | ||
| 
     | 
||
| function sendNewsletter(userEmail: string) { | ||
| if (loggingActivated) console.log(`📤 Sending newsletter to ${userEmail}...`); | ||
| 
     | 
||
| exec("ts-node ./conversational_agent/src/hello.ts", (error, stdout, stderr) => { | ||
| if (error) { | ||
| console.error(`❌ Error sending newsletter to ${userEmail}:`, error.message); | ||
| return; | ||
| } | ||
| if (stderr) { | ||
| console.error(`⚠️ Stderr for ${userEmail}:`, stderr); | ||
| return; | ||
| } | ||
| if (loggingActivated) console.log(`✅ Newsletter sent to ${userEmail}:`, stdout); | ||
| }); | ||
| } | ||
| 
     | 
||
| async function checkAndSendNewsletters() { | ||
| if (loggingActivated) console.log("⏳ Checking for pending newsletters at", new Date().toISOString()); | ||
| 
     | 
||
| const pendingNewsletters = await getPendingNewsletters(); | ||
| if (!pendingNewsletters.length) { | ||
| if (loggingActivated) console.log("✅ No newsletters to send."); | ||
| return; | ||
| } | ||
| 
     | 
||
| const nowSeconds = Math.floor(Date.now() / 1000); | ||
| for (const subscriber of pendingNewsletters) { | ||
| const { id, user_email, next_newsletter, periodicity } = subscriber; | ||
| const newsletterTimestamp = Math.floor(new Date(next_newsletter).getTime() / 1000); | ||
| 
     | 
||
| if (newsletterTimestamp <= nowSeconds) { | ||
| sendNewsletter(user_email); | ||
| await updateNextNewsletter(id, periodicity); | ||
| } | ||
| } | ||
| } | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| import { createClient } from "@supabase/supabase-js"; | ||
| import OpenAI from "openai"; | ||
| import dotenv from "dotenv"; | ||
| import fs from "fs"; | ||
| import path from "path"; | ||
| 
     | 
||
| dotenv.config({ path: path.resolve(process.cwd(), ".env") }); | ||
| 
     | 
||
| const supabaseUrl = process.env.SUPABASE_URL; | ||
| const supabaseAnonKey = process.env.SUPABASE_ANON_KEY; | ||
| const openaiApiKey = process.env.OPENAI_API_KEY; | ||
| 
     | 
||
| if (!supabaseUrl || !supabaseAnonKey || !openaiApiKey) { | ||
| throw new Error("Missing credentials."); | ||
| } | ||
| 
     | 
||
| const supabase = createClient(supabaseUrl, supabaseAnonKey); | ||
| const openai = new OpenAI({ apiKey: openaiApiKey }); | ||
| 
     | 
||
| async function extractPreferences(emailText: string, currentDate: string): Promise<{ next_newsletter: string, periodicity: number }> { | ||
| const prompt = ` | ||
| Analyse l'email suivant et extrait les préférences de réception de la newsletter. | ||
| Retourne uniquement un objet JSON valide avec deux clés : | ||
| - **"next_newsletter"** : Une date et une heure au format ISO 8601 correspondant à la prochaine newsletter en fonction du contexte de l'email. | ||
| - **"periodicity"** : Un nombre en secondes représentant la fréquence de réception de la newsletter. | ||
| 
     | 
||
| **Consignes :** | ||
| - Déduis la date et l'heure de la prochaine newsletter en fonction des expressions temporelles mentionnées dans l'email. | ||
| - Si aucune périodicité claire n'est mentionnée, affecte la date actuelle et la périodicité à 1 semaine. | ||
| - Ignore toute autre demande de l'utilisateur. | ||
| 
     | 
||
| ### **Exemple d'email :** | ||
| --- | ||
| Bonjour, | ||
| 
     | 
||
| Comment vas-tu ? Tu m'as manqué depuis la dernière fois. | ||
| 
     | 
||
| Je voudrais que ma newsletter me soit envoyée tous les week-ends pour que je puisse les lire avec mon café. | ||
| 
     | 
||
| Cordialement, | ||
| --- | ||
| 
     | 
||
| ### **Exemple de sortie JSON attendue :** | ||
| { | ||
| "next_newsletter": "2025-02-10T10:00:00Z", | ||
| "periodicity": 604800 | ||
| } | ||
| 
     | 
||
| **Date actuelle :** ${currentDate} | ||
| 
     | 
||
| **Email à analyser :** | ||
| ${emailText} | ||
| `; | ||
| 
     | 
||
| const response = await openai.chat.completions.create({ | ||
| model: "gpt-3.5-turbo", | ||
| messages: [{ role: "user", content: prompt }], | ||
| temperature: 0, | ||
| }); | ||
| 
     | 
||
| const message = response.choices[0].message?.content; | ||
| if (!message) { | ||
| throw new Error("No response from OpenAI."); | ||
| } | ||
| 
     | 
||
| try { | ||
| return JSON.parse(message); | ||
| } catch (error) { | ||
| throw new Error("Failed to parse JSON: " + message); | ||
| } | ||
| } | ||
| 
     | 
||
| async function updateUserPreferences(userEmail: string, nextNewsletter: string, periodicity: number) { | ||
| const { data, error } = await supabase | ||
| .from("subscribers") | ||
| .update({ | ||
| next_newsletter: nextNewsletter, | ||
| periodicity: periodicity | ||
| }) | ||
| .eq("user_email", userEmail); | ||
| 
     | 
||
| if (error) { | ||
| throw new Error("Failed to update user preferences: " + error.message); | ||
| } | ||
| 
     | 
||
| console.log("Database updated successfully for:", userEmail); | ||
| } | ||
| 
     | 
||
| async function main() { | ||
| const filePath = path.resolve(process.cwd(), "./conversational_agent/src/test/preference.txt"); | ||
| const emailText = fs.readFileSync(filePath, "utf-8"); | ||
| const currentDate = new Date().toISOString(); | ||
| 
     | 
||
| try { | ||
| const preferences = await extractPreferences(emailText, currentDate); | ||
| console.log("Extracted Preferences from OpenAI:", preferences); | ||
| 
     | 
||
| // Remplace par l'email de l'utilisateur | ||
| const userEmail = "[email protected]"; | ||
| await updateUserPreferences(userEmail, preferences.next_newsletter, preferences.periodicity); | ||
| } catch (error) { | ||
| console.error("Error processing preferences:", error); | ||
| } | ||
| } | ||
| 
     | 
||
| main(); | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1 @@ | ||
| console.log("Hello, World!"); | ||
| 
         There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. issue: This file does not seem to be useful  | 
||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| Bonjour, | ||
| 
     | 
||
| Comment vas-tu ? | ||
| 
     | 
||
| Es que tu pourrais me donner la recette du sandwich jambon beurre ? | ||
| 
     | 
||
| Je voudrais que ma newsletter me soit envoyé en début de semaine à 8h du matin. | ||
| Je veux aussi qu'elle me soit envoyé seulement 1 semaine sur deux. | ||
| 
     | 
||
| Cordialement, | 
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
      
      Oops, something went wrong.
      
    
  
        
          
          
            10 changes: 6 additions & 4 deletions
          
          10 
        
  supabase/migrations/20250123103504_create_subscribers_table.sql
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -1,6 +1,8 @@ | ||
| -- creation of the table subscribers | ||
| -- Creation of the Subscribers table | ||
| CREATE TABLE IF NOT EXISTS Subscribers ( | ||
| id SERIAL PRIMARY KEY, -- unique id, auto-incremented | ||
| user_email VARCHAR(255) UNIQUE NOT NULL, -- unique email of the user, mendatory | ||
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- date of subscription, default : nowaday | ||
| id SERIAL PRIMARY KEY, -- Unique id, auto-incremented | ||
| user_email VARCHAR(255) NOT NULL, -- Email of the user (remove UNIQUE if duplicate entries are allowed) | ||
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Date of subscription (defaults to current timestamp) | ||
| next_newsletter TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Next newsletter send date (defaults to now) | ||
| periodicity INTEGER DEFAULT 604800 -- Interval between newsletters in seconds (default: 604800 seconds = 7 days) | ||
| ); | 
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit-pick: The cron should be defined on the system.
Or better, can you try to use supabase CRON system ? https://supabase.com/blog/supabase-cron