1export default async (c, next) => {
2 const secret = c.req.header("x-api-key");
3 const method = c.req.method;
4 if (secret !== Deno.env.get("X_API_KEY") && method !== "GET") {
5 return c.text("Unauthorized", 401);
6 }
1# Val Town REST API TypeScript SDK Demos
2
3This val demonstrates basic usage of the the Val Town JS/TS SDK.
5You can fork this val to your account to quickly try it out.
6
7Authentication is automatically set by the `VAL_TOWN_API_KEY` environment
8variable, which is automatically set within Val Town. You can control the
9API scopes of that key in your val's settings page.
10
11* [Learn more](https://docs.val.town/sdk/)
12* [Reference docs](https://github.com/val-town/sdk/blob/main/api.md)
86
87/**
88 * Format chat history for Anthropic API
89 */
90function formatChatHistoryForAI(history) {
314bot.on("message", async (ctx) => {
315 try {
316 // Get Anthropic API key from environment
317 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
318 if (!apiKey) {
319 console.error("Anthropic API key is not configured.");
320 ctx.reply(
321 "I apologize, but I'm not properly configured at the moment. Please inform the household administrator.",
325
326 // Initialize Anthropic client
327 const anthropic = new Anthropic({ apiKey });
328
329 // Get message text and user info
491 // Set webhook if it is not set yet
492 if (!isEndpointSet) {
493 await bot.api.setWebhook(req.url, {
494 secret_token: SECRET_TOKEN,
495 });
2import { OpenAI } from "https://esm.town/v/std/openai";
3
4// Constants for location and API base URL
5const LATITUDE: number = 45.6333;
6const LONGITUDE: number = 8.9167;
7const OPEN_METEO_BASE_URL: string = "https://api.open-meteo.com/v1/forecast";
8
9// Telegram Bot Configuration
42
43/**
44 * Interface for OpenMeteo API weather response
45 */
46interface OpenMeteoWeatherResponse {
66/**
67 * Interprets OpenMeteo weather codes into human-readable descriptions
68 * @param code Numeric weather code from OpenMeteo API
69 * @returns Object with description and emoji representation
70 */
101
102/**
103 * Build detailed weather information from OpenMeteo API response
104 * @param weatherData Raw weather data from OpenMeteo
105 * @returns Structured WeatherDetails object
148 role: "system",
149 content:
150 "Sei un esperto di meteorologia. Il tuo compito è riassumere i dati forniti in formato JSON dalle API di Open-meteo.com in modo simpatico e comprensibile. I dati contengono le condizioni meteo attuali e il forecast dell'intera giornata, spalmati su 24 ore. Usa un tono colloquiale e due o tre frasi al massimo per il riassunto.",
151 },
152 {
188 })
189 .then(summary => {
190 bot.api.sendMessage(CHAT_ID, summary);
191 });
192}
166bot.on("message", async (ctx) => {
167 try {
168 const OPENAI_KEY = Deno.env.get("OPENAI_API_KEY");
169 if (!OPENAI_KEY) {
170 console.error("OPENAI_API_KEY is not configured.");
171 await ctx.reply("I apologize, but I am not properly configured at present.");
172 return;
173 }
174
175 const openai = new OpenAI({ apiKey: OPENAI_KEY });
176
177 const messageText = ctx.message.text ?? "";
263export default async function(req: Request): Promise<Response> {
264 if (!isEndpointSet) {
265 await bot.api.setWebhook(req.url, { secret_token: SECRET_TOKEN });
266 isEndpointSet = true;
267 }
66// -----------------------------------------------------------------------------
67async function generateFunFacts(previousFacts: { date: string; text: string }[]) {
68 const apiKey = Deno.env.get("OPENAI_API_KEY");
69 if (!apiKey) {
70 console.error("OPENAI_API_KEY is not configured.");
71 return [];
72 }
73
74 const openai = new OpenAI({ apiKey });
75
76 // Build auxiliary strings for the prompt
26 */
27async function generateConciseWeatherSummary(weatherDay: ReturnType<typeof summarizeWeather>[number]) {
28 const apiKey = Deno.env.get("OPENAI_API_KEY");
29 if (!apiKey) {
30 console.error("OPENAI_API_KEY is not configured.");
31 return null;
32 }
33
34 const openai = new OpenAI({ apiKey });
35
36 const systemPrompt = `You are a weather forecaster. Create a very concise summary of a day's forecast.`;
96 today?: DateTime,
97) {
98 // Get API keys from environment
99 const apiKey = Deno.env.get("OPENAI_API_KEY");
100 const telegramToken = Deno.env.get("TELEGRAM_TOKEN");
101
105 }
106
107 if (!apiKey) {
108 console.error("OPENAI_API_KEY is not configured.");
109 return;
110 }
121
122 // Initialize OpenAI client
123 const openai = new OpenAI({ apiKey });
124
125 // Initialize Telegram bot
152
153 const sendChunk = async (chunk: string) => {
154 await bot.api.sendMessage(chatId!, chunk, { parse_mode: "Markdown" });
155 await storeChatMessage(chatId!, BOT_SENDER_ID, BOT_SENDER_NAME, chunk, true);
156 };
92
93/**
94The http action sends a HTTP request when the action button is tapped. You can use this to trigger REST APIs for whatever systems you have, e.g. opening the garage door, or turning on/off lights.
95**/
96export interface HTTPAction {
53You'll need to set up some environment variables to make it run.
54
55- `ANTHROPIC_API_KEY` for LLM calls
56- You'll need to follow [these instructions](https://docs.val.town/integrations/telegram/) to make a telegram bot, and set `TELEGRAM_TOKEN`. You'll also need to get a `TELEGRAM_CHAT_ID` in order to have the bot remember chat contents.
57- For the Google Calendar integration you'll need `GOOGLE_CALENDAR_ACCOUNT_ID` and `GOOGLE_CALENDAR_CALENDAR_ID`. See [these instuctions](https://www.val.town/v/stevekrouse/pipedream) for details.