Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/image-url.jpg%20%22Optional%20title%22?q=function&page=7&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 18483 results for "function"(1849ms)

Discord_Bot_Servicesscheduled-maintenance.tsx8 matches

@ktodaz•Updated 2 hours ago
5
6// Setup the database if needed
7async function setupDatabase() {
8 await sqlite.execute(`
9 CREATE TABLE IF NOT EXISTS channels (
20
21// Track a channel creation
22async function trackChannel(channelId: string, name: string, guildId: string, categoryId?: string) {
23 await sqlite.execute({
24 sql: `INSERT INTO channels (id, name, guild_id, category_id) VALUES (?, ?, ?, ?)`,
30
31// Get recent channels
32async function getRecentChannels() {
33 const result = await sqlite.execute(`
34 SELECT * FROM channels
47
48// Cleanup old channels if needed
49async function cleanupOldChannels() {
50 // This is a placeholder for actual cleanup logic
51 // In a real implementation, you might want to:
58}
59
60// Heartbeat function to check Discord API connection
61async function heartbeat() {
62 const DISCORD_BOT_TOKEN = Deno.env.get("DISCORD_BOT_TOKEN");
63
83}
84
85// Main function to run maintenance tasks
86export default async function() {
87 console.log("Starting scheduled maintenance...");
88

Townieusage-dashboard.ts4 matches

@valdottown•Updated 2 hours ago
4
5// Basic Auth middleware
6async function basicAuthMiddleware(req: Request): Promise<Response | null> {
7 const realm = "Usage Dashboard";
8 const unauthorizedResponse = new Response("Unauthorized", {
50}
51
52export default async function(req: Request) {
53 // Check authentication first
54 const authResponse = await basicAuthMiddleware(req);
288
289 <script>
290 document.addEventListener('DOMContentLoaded', function() {
291 // Add click event listeners to all tabs
292 document.querySelectorAll('.tab').forEach(tab => {
293 tab.addEventListener('click', function() {
294 const tabId = this.getAttribute('data-tab');
295

Discord_Bot_Servicesregister-commands.tsx3 matches

@ktodaz•Updated 2 hours ago
31];
32
33async function registerCommands() {
34 if (!DISCORD_APP_ID) {
35 throw new Error("Missing DISCORD_APP_ID environment variable");
68}
69
70// This function will be called when this val is run directly
71export default async function() {
72 try {
73 const result = await registerCommands();

MainMain.tsx1 match

@Get•Updated 2 hours ago
1export default async function (req: Request): Promise<Response> {
2 return Response.json({ ok: true })
3}

EEPMOnitoringweeklyReport.tsx4 matches

@solomonferede•Updated 2 hours ago
5};
6
7function WeeklyReportTab() {
8 // State for the detailed report (news and media)
9 const [detailedReport, setDetailedReport] = useState(null);
28 const itemsPerPage = 5; // Items per page for detailed reports
29
30 // Function to generate the detailed report
31 const generateDetailedReport = async () => {
32 setDetailedReport(null); // Clear previous data
43 };
44
45 // Function to generate the weekly summary report
46 const generateWeeklySummary = async () => {
47 setWeeklySummary(null); // Clear previous data
90 }, [filteredMonitorings, mediaPage]);
91
92 // Helper function for CSV export (only for detailed report)
93 const exportToCSV = (data, filename) => {
94 if (!data || data.length === 0) {

EEPMOnitoringApp.tsx7 matches

@solomonferede•Updated 3 hours ago
25};
26
27// --- Helper Functions ---
28async function hashPassword(password) {
29 const encoder = new TextEncoder();
30 const data = encoder.encode(password);
36
37// --- Main App Component ---
38function App() {
39 const [user, setUser] = useState(null);
40 const [view, setView] = useState("login"); // 'login', 'news', 'media', 'report'
247Client-side Entry Point
248==========================*/
249function client() {
250 const rootElement = document.getElementById("root");
251 if (rootElement) {
263Server-side Logic (Val Town / Deno Deploy)
264==========================*/
265// The server function remains the same as in the previous single-file solution,
266// as it handles API requests and serves the main HTML.
267// Its logic is independent of how the client-side components are structured into files.
268export default async function server(
269 request, /*: Request // Removed type for broader compatibility if not in TS env */
270) /*: Promise<Response>*/ {
638 if (path === "/" && method === "GET") {
639 // The module script src will be this file itself.
640 // The client() function will be called.
641 // The component imports like "./components/login.tsx" will be resolved by the environment
642 // (e.g., Val Town's bundler or a local dev server/bundler).

stevensDemotestDailyBrief.ts1 match

@lm3m•Updated 3 hours ago
4import { DateTime } from "https://esm.sh/luxon@3.4.4";
5
6export async function testDailyBrief() {
7 try {
8 const testChatId = Deno.env.get("TEST_TELEGRAM_CHAT_ID");

stevensDemosetupTelegramChatDb.ts1 match

@lm3m•Updated 3 hours ago
2// Run this script manually to create the database table
3
4export default async function setupTelegramChatDb() {
5 try {
6 // Import SQLite module

stevensDemosendDailyBrief.ts6 matches

@lm3m•Updated 3 hours ago
13} from "../memoryUtils.ts";
14
15async function generateBriefingContent(anthropic, memories, today, isSunday) {
16 try {
17 const weekdaysHelp = generateWeekDays(today);
96}
97
98export async function sendDailyBriefing(chatId?: string, today?: DateTime) {
99 // Get API keys from environment
100 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
135 const lastSunday = today.startOf("week").minus({ days: 1 });
136
137 // Fetch relevant memories using the utility function
138 const memories = await getRelevantMemories();
139
216}
217
218function generateWeekDays(today) {
219 let output = [];
220
239// console.log(weekDays);
240
241// Export a function that calls sendDailyBriefing with no parameters
242// This maintains backward compatibility with existing cron jobs
243export default async function (overrideToday?: DateTime) {
244 return await sendDailyBriefing(undefined, overrideToday);
245}

stevensDemoREADME.md2 matches

@lm3m•Updated 3 hours ago
16In a normal server environment, you would likely use a middleware [like this one](https://hono.dev/docs/getting-started/nodejs#serve-static-files) to serve static files. Some frameworks or deployment platforms automatically make any content inside a `public/` folder public.
17
18However in Val Town you need to handle this yourself, and it can be suprisingly difficult to read and serve files in a Val Town Project. This template uses helper functions from [stevekrouse/utils/serve-public](https://www.val.town/x/stevekrouse/utils/branch/main/code/serve-public/README.md), which handle reading project files in a way that will work across branches and forks, automatically transpiles typescript to javascript, and assigns content-types based on the file's extension.
19
20### `index.html`
26## CRUD API Routes
27
28This app has two CRUD API routes: for reading and inserting into the messages table. They both speak JSON, which is standard. They import their functions from `/backend/database/queries.ts`. These routes are called from the React app to refresh and update data.
29
30## Errors

getFileEmail4 file matches

@shouser•Updated 2 weeks ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblk•Updated 2 weeks ago
Simple functional CSS library for Val Town
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.